comment
stringlengths
1
45k
method_body
stringlengths
23
281k
target_code
stringlengths
0
5.16k
method_body_after
stringlengths
12
281k
context_before
stringlengths
8
543k
context_after
stringlengths
8
543k
What will 'throw' achieve here ?
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
throw logger.logExceptionAsError(new CredentialUnavailableException(
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
This logic is not correct, we only want to catch CredentialUnavailableException here.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
.flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> {
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
We seem to be double logging the exception here.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
throw logger.logExceptionAsError(new CredentialUnavailableException(
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
A single large message will be unfriendly to read. Are we doing this across all languages ? Better to keep the individual exceptions and their stack trace separate
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
message.append(t.getMessage()).append(" ");
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
In this pr, I change java error message to java(new), and other languages' error message is now as follow, Do java need change it to java(new)? If you think java need change and the java(new) error message is not good enough, please change it in the under table , and I will implement. Scenario | Python/C# | Java(Current) | Java(new) -- | -- | -- | -- Credential Unavailable | DefaultAzureCredential failed to retrieve a token from the included credentials. EnvironmentCredential authentication unavailable. Environment variables are not fully configured. ManagedIdentityCredential authentication unavailable. No Managed Identity endpoint found. SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache. | Tried EnvironmentCredential, ManagedIdentityCredential, SharedTokenCacheCredential, AzureCliCredential but failed to acquire a token for any of them. Please verify the environment for the credentials and see more details in the causes below. | DefaultAzureCredential failed to retrieve a token from the included credentials.EnvironmentCredential authentication unavailable. Environment variables are not fully configured. ManagedIdentityCredential authentication unavailable. Connection to IMDS endpoint cannot be established, connect timed out. SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache. AzureCliCredential authentication unavailable. Authenticate Failed | DefaultAzureCredential authentication failed. ---> Azure.Identity.AuthenticationFailedException: ClientSecretCredential authentication failed. ---> Azure.RequestFailedException: Service request failed. Status: 400 (Bad Request) Content: {"error":"unauthorized_client","error_description":"AADSTS700016: Application with identifier '78e8f606-0950-4210-906d-1d321511c09d' was not found in the directory 'a7fc734e-9961-43ce-b4de-21b8b38403ba'. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You may have sent your authentication request to the wrong tenant.\r\nTrace ID: 9f3624a7-49ca-4097-a339-780fd4e41600\r\nCorrelation ID: b1acfa40-06cc-42a1-a2f1-d35b94db3628\r\nTimestamp: 2020-02-06 01:13:33Z","error_codes":[700016],"timestamp":"2020-02-06 01:13:33Z","trace_id":"9f3624a7-49ca-4097-a339-780fd4e41600","correlation_id":"b1acfa40-06cc-42a1-a2f1-d35b94db3628","error_uri":"https://login.microsoftonline.com/error?code=700016"} | Tried EnvironmentCredential, ManagedIdentityCredential, SharedTokenCacheCredential, AzureCliCredential but failed to acquire a token for any of them. Please verify the environment for the credentials and see more details in the causes below. | DefaultAzureCredential authentication failed. ---> EnvironmentCredential authentication failed. …….  Suppressed: com.microsoft.aad.msal4j.MsalServiceException: AADSTS90002: Tenant '72f988bf-86f1-41af-91ab-2d7cd011db41' not found. This may happen if there are no active subscriptions for the tenant. Check to make sure you have the correct tenant ID. Check with your subscription administrator.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
message.append(t.getMessage()).append(" ");
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
In the reactive spec, this should return normally rather than throwing (ie. `return Mono.error(logger.logExceptionAsError)`). https://github.com/reactive-streams/reactive-streams-jvm#2.13
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
throw logger.logExceptionAsError(new CredentialUnavailableException(
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
This if statement logic is redundant now. can be removed.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t))); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) {
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
We need to retain the stack traces from individual exception and chain them. Java devs use the stack trace to analyze / debug issues.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { throw logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
message.append(t.getMessage()).append(" ");
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
In .net python and js, if authenticate unavaliable, continuing to run follow credential. If authenticate failed, stop running and print the failed credential and its failed reason.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t))); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) {
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
Yeah, the onErrorResume will only get invoked if CredentialUnavailabeException is thrown. A non CredentialUnavailabeException will never reach this block and will automatically break the chain. So, this check in the if statement for a non CredentialUnavailabeException is not needed as a non CredentialUnavailabeException will never enter this block now.
public Mono<AccessToken> getToken(TokenRequestContext request) { StringBuilder message = new StringBuilder(); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(logger.logExceptionAsError(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t))); } message.append(t.getMessage()).append(" "); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { return Mono.error(new CredentialUnavailableException(message.toString())); })); }
if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) {
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final ClientLogger logger = new ClientLogger(ChainedTokenCredential.class); private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
WHat does the error message with stack trace look like now ? Can you post the sample output here ?
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + " " + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
return Mono.error(last);
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
Exception in thread "main" java.lang.RuntimeException: Max retries 3 times exceeded. Error Details: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. ManagedIdentityCredential authentication unavailable. Connection to IMDS endpoint cannot be established, Network is unreachable: connect. SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache. IntelliJ Authentication not available. Please log in with Azure Tools for IntelliJ plugin in the IDE. Failed to read Vs Code credentials from Windows Credential API. AzureCliCredential authentication unavailable. Azure CLI not installed at com.azure.core.http.policy.RetryPolicy.lambda$attemptAsync$1(RetryPolicy.java:119) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:88) at reactor.core.publisher.MonoFlatMap$FlatMapMain.onError(MonoFlatMap.java:165) at reactor.core.publisher.MonoFlatMap$FlatMapMain.onError(MonoFlatMap.java:165) at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:185) at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:251) at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onError(MonoPeekTerminal.java:251) at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onError(MonoPeekTerminal.java:251) at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onError(FluxPeekFuseable.java:894) at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onError(FluxPeekFuseable.java:894) at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onError(Operators.java:1994) at reactor.core.publisher.Operators.error(Operators.java:196) at reactor.core.publisher.MonoError.subscribe(MonoError.java:52) at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:52) at reactor.core.publisher.Mono.subscribe(Mono.java:4218) at reactor.core.publisher.FluxSwitchIfEmpty$SwitchIfEmptySubscriber.onComplete(FluxSwitchIfEmpty.java:75) at reactor.core.publisher.MonoNext$NextSubscriber.onComplete(MonoNext.java:96) at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:838) at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:600) at reactor.core.publisher.FluxFlatMap$FlatMapMain.innerComplete(FluxFlatMap.java:909) at reactor.core.publisher.FluxFlatMap$FlatMapInner.onComplete(FluxFlatMap.java:1013) at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onComplete(Operators.java:1989) at reactor.core.publisher.Operators.complete(Operators.java:135) at reactor.core.publisher.MonoEmpty.subscribe(MonoEmpty.java:45) at reactor.core.publisher.Mono.subscribe(Mono.java:4218) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:97) at reactor.core.publisher.FluxMap$MapSubscriber.onError(FluxMap.java:126) at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onError(Operators.java:1994) at reactor.core.publisher.MonoFlatMap$FlatMapMain.onNext(MonoFlatMap.java:135) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onNext(FluxOnErrorResume.java:73) at reactor.core.publisher.Operators$MonoSubscriber.complete(Operators.java:1755) at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:86) at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1705) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1692) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177) Suppressed: java.lang.Exception: #block terminated with an error at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99) at reactor.core.publisher.Mono.block(Mono.java:1678) at com.azure.security.keyvault.secrets.SecretClient.setSecretWithResponse(SecretClient.java:113) at com.azure.security.keyvault.secrets.SecretClient.setSecret(SecretClient.java:93) at com.azure.identity.Test.main(Test.java:31) Caused by: com.azure.identity.CredentialUnavailableException: EnvironmentCredential authentication unavailable. Environment variables are not fully configured. ManagedIdentityCredential authentication unavailable. Connection to IMDS endpoint cannot be established, Network is unreachable: connect. SharedTokenCacheCredential authentication unavailable. No accounts were found in the cache. IntelliJ Authentication not available. Please log in with Azure Tools for IntelliJ plugin in the IDE. Failed to read Vs Code credentials from Windows Credential API. AzureCliCredential authentication unavailable. Azure CLI not installed at com.azure.identity.ChainedTokenCredential.lambda$2(ChainedTokenCredential.java:58) at reactor.core.publisher.MonoDefer.subscribe(MonoDefer.java:44) ... 28 more
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + " " + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
return Mono.error(last);
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
if failed: Exception in thread "main" java.lang.RuntimeException: Max retries 3 times exceeded. Error Details: DefaultAzureCredential authentication failed. ---> EnvironmentCredential authentication failed. Error Details:AADSTS90002: Tenant '72f988bf-86f1-41af-91ab-2d7cd011db46' not found. This may happen if there are no active subscriptions for the tenant. Check to make sure you have the correct tenant ID. Check with your subscription administrator. Trace ID: 43ffc9ad-f468-4665-ac3a-14a278a98600 Correlation ID: e3d3e754-89f0-4839-870c-57e6aba9a5f0 Timestamp: 2020-06-08 01:49:43Z at com.azure.core.http.policy.RetryPolicy.lambda$attemptAsync$1(RetryPolicy.java:119) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:88) at reactor.core.publisher.MonoFlatMap$FlatMapMain.onError(MonoFlatMap.java:165) at reactor.core.publisher.MonoFlatMap$FlatMapMain.onError(MonoFlatMap.java:165) at reactor.core.publisher.MonoFlatMap$FlatMapMain.secondError(MonoFlatMap.java:185) at reactor.core.publisher.MonoFlatMap$FlatMapInner.onError(MonoFlatMap.java:251) at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onError(MonoPeekTerminal.java:251) at reactor.core.publisher.MonoPeekTerminal$MonoTerminalPeekSubscriber.onError(MonoPeekTerminal.java:251) at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onError(FluxPeekFuseable.java:894) at reactor.core.publisher.FluxPeekFuseable$PeekConditionalSubscriber.onError(FluxPeekFuseable.java:894) at reactor.core.publisher.Operators$MultiSubscriptionSubscriber.onError(Operators.java:1994) at reactor.core.publisher.MonoNext$NextSubscriber.onError(MonoNext.java:87) at reactor.core.publisher.FluxFlatMap$FlatMapMain.checkTerminated(FluxFlatMap.java:834) at reactor.core.publisher.FluxFlatMap$FlatMapMain.drainLoop(FluxFlatMap.java:600) at reactor.core.publisher.FluxFlatMap$FlatMapMain.drain(FluxFlatMap.java:580) at reactor.core.publisher.FluxFlatMap$FlatMapMain.innerError(FluxFlatMap.java:855) at reactor.core.publisher.FluxFlatMap$FlatMapInner.onError(FluxFlatMap.java:1006) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:100) at reactor.core.publisher.Operators.error(Operators.java:196) at reactor.core.publisher.MonoError.subscribe(MonoError.java:52) at reactor.core.publisher.Mono.subscribe(Mono.java:4218) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:97) at reactor.core.publisher.FluxMapFuseable$MapFuseableSubscriber.onError(FluxMapFuseable.java:134) at reactor.core.publisher.MonoCompletionStage.lambda$subscribe$0(MonoCompletionStage.java:80) at java.base/java.util.concurrent.CompletableFuture.uniWhenComplete(CompletableFuture.java:859) at java.base/java.util.concurrent.CompletableFuture$UniWhenComplete.tryFire(CompletableFuture.java:837) at java.base/java.util.concurrent.CompletableFuture.postComplete(CompletableFuture.java:506) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1705) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.exec(CompletableFuture.java:1692) at java.base/java.util.concurrent.ForkJoinTask.doExec(ForkJoinTask.java:290) at java.base/java.util.concurrent.ForkJoinPool$WorkQueue.topLevelExec(ForkJoinPool.java:1020) at java.base/java.util.concurrent.ForkJoinPool.scan(ForkJoinPool.java:1656) at java.base/java.util.concurrent.ForkJoinPool.runWorker(ForkJoinPool.java:1594) at java.base/java.util.concurrent.ForkJoinWorkerThread.run(ForkJoinWorkerThread.java:177) Suppressed: java.lang.Exception: #block terminated with an error at reactor.core.publisher.BlockingSingleSubscriber.blockingGet(BlockingSingleSubscriber.java:99) at reactor.core.publisher.Mono.block(Mono.java:1678) at com.azure.security.keyvault.secrets.SecretClient.setSecretWithResponse(SecretClient.java:113) at com.azure.security.keyvault.secrets.SecretClient.setSecret(SecretClient.java:93) at com.azure.identity.Test.main(Test.java:31) Caused by: com.azure.identity.CredentialUnavailableException: DefaultAzureCredential authentication failed. ---> EnvironmentCredential authentication failed. Error Details:AADSTS90002: Tenant '72f988bf-86f1-41af-91ab-2d7cd011db46' not found. This may happen if there are no active subscriptions for the tenant. Check to make sure you have the correct tenant ID. Check with your subscription administrator. Trace ID: 43ffc9ad-f468-4665-ac3a-14a278a98600 Correlation ID: e3d3e754-89f0-4839-870c-57e6aba9a5f0 Timestamp: 2020-06-08 01:49:43Z at com.azure.identity.ChainedTokenCredential.lambda$1(ChainedTokenCredential.java:44) at reactor.core.publisher.Mono.lambda$onErrorResume$31(Mono.java:3360) at reactor.core.publisher.FluxOnErrorResume$ResumeSubscriber.onError(FluxOnErrorResume.java:88) ... 12 more Caused by: com.microsoft.aad.msal4j.MsalServiceException: AADSTS90002: Tenant '72f988bf-86f1-41af-91ab-2d7cd011db46' not found. This may happen if there are no active subscriptions for the tenant. Check to make sure you have the correct tenant ID. Check with your subscription administrator. Trace ID: 43ffc9ad-f468-4665-ac3a-14a278a98600 Correlation ID: e3d3e754-89f0-4839-870c-57e6aba9a5f0 Timestamp: 2020-06-08 01:49:43Z at com.microsoft.aad.msal4j.MsalServiceExceptionFactory.fromHttpResponse(MsalServiceExceptionFactory.java:43) at com.microsoft.aad.msal4j.TokenRequestExecutor.createAuthenticationResultFromOauthHttpResponse(TokenRequestExecutor.java:81) at com.microsoft.aad.msal4j.TokenRequestExecutor.executeTokenRequest(TokenRequestExecutor.java:36) at com.microsoft.aad.msal4j.ClientApplicationBase.acquireTokenCommon(ClientApplicationBase.java:92) at com.microsoft.aad.msal4j.AcquireTokenByAuthorizationGrantSupplier.execute(AcquireTokenByAuthorizationGrantSupplier.java:52) at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:59) at com.microsoft.aad.msal4j.AuthenticationResultSupplier.get(AuthenticationResultSupplier.java:17) at java.base/java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1700) ... 6 more
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(CredentialUnavailableException.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed.", t)); } exceptions.add(t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + " " + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
return Mono.error(last);
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
Why are we wrapping a non Credential Unavailable Exception into a Credential Unavailable Exception ? It should be thrown as it is, to indicate a genuine exception even though credential is available to be used. The distinction will help to debug customer issues too in future.
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new CredentialUnavailableException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + " " + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
return Mono.error(new CredentialUnavailableException(
public Mono<AccessToken> getToken(TokenRequestContext request) { List<CredentialUnavailableException> exceptions = new ArrayList<>(4); return Flux.fromIterable(credentials) .flatMap(p -> p.getToken(request).onErrorResume(Exception.class, t -> { if (!t.getClass().getSimpleName().equals("CredentialUnavailableException")) { return Mono.error(new ClientAuthenticationException( unavailableError + p.getClass().getSimpleName() + " authentication failed. Error Details: " + t.getMessage(), null, t)); } exceptions.add((CredentialUnavailableException) t); return Mono.empty(); }), 1) .next() .switchIfEmpty(Mono.defer(() -> { CredentialUnavailableException last = exceptions.get(exceptions.size() - 1); for (int z = exceptions.size() - 2; z >= 0; z--) { CredentialUnavailableException current = exceptions.get(z); last = new CredentialUnavailableException(current.getMessage() + "\r\n" + last.getMessage(), last.getCause()); } return Mono.error(last); })); }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
class ChainedTokenCredential implements TokenCredential { private final Deque<TokenCredential> credentials; private final String unavailableError = this.getClass().getSimpleName() + " authentication failed. ---> "; /** * Create an instance of chained token credential that aggregates a list of token * credentials. */ ChainedTokenCredential(Deque<TokenCredential> credentials) { this.credentials = credentials; } @Override }
.map is sufficient since this is not an asynchronous operation. Also replace usage of System.out with logger
public Mono<Long> scheduleMessage(ServiceBusMessage message, Instant scheduledEnqueueTime) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(scheduledEnqueueTime, "'scheduledEnqueueTime' cannot be null."); return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName)) .flatMap(x -> x.schedule(message, scheduledEnqueueTime)) .flatMap(scheduleSequenceNumber -> { System.out.println(getClass().getName() + ".schedule scheduleSequenceNumber = " + scheduleSequenceNumber); return Mono.just(scheduleSequenceNumber); }); }
.flatMap(scheduleSequenceNumber -> {
public Mono<Long> scheduleMessage(ServiceBusMessage message, Instant scheduledEnqueueTime) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(scheduledEnqueueTime, "'scheduledEnqueueTime' cannot be null."); return getSendLink() .flatMap(link -> link.getLinkSize().flatMap(size -> { int maxSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMap(managementNode -> managementNode.schedule(message, scheduledEnqueueTime, maxSize)); })); }
class ServiceBusSenderAsyncClient implements Closeable { private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final AmqpRetryOptions retryOptions; private final AmqpRetryPolicy retryPolicy; private final String entityName; private final ServiceBusConnectionProcessor connectionProcessor; /** * The default maximum allowable size, in bytes, for a batch to be sent. */ public static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024; /** * Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to */ ServiceBusSenderAsyncClient(String entityName, ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = tracerProvider; this.retryPolicy = getRetryPolicy(retryOptions); } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityName() { return entityName; } /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * * @return The {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); return sendInternal(Flux.just(message)); } /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * @param sessionId the session id to associate with the message. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} or {@code sessionId} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message, String sessionId) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(sessionId, "'sessionId' cannot be null."); return Mono.error(new IllegalStateException("Not implemented.")); } /** * Sends a message batch to the Azure Service Bus entity this sender is connected to. * * @param batch of messages which allows client to send maximum allowed size for a batch of messages. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code batch} is {@code null}. */ public Mono<Void> send(ServiceBusMessageBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); final boolean isTracingEnabled = tracerProvider.isEnabled(); final AtomicReference<Context> parentContext = isTracingEnabled ? new AtomicReference<>(Context.NONE) : null; if (batch.getMessages().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } logger.info("Sending batch with size[{}].", batch.getCount()); Context sharedContext = null; final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>(); for (int i = 0; i < batch.getMessages().size(); i++) { final ServiceBusMessage event = batch.getMessages().get(i); if (isTracingEnabled) { parentContext.set(event.getContext()); if (i == 0) { sharedContext = tracerProvider.getSharedSpanBuilder(parentContext.get()); } tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext())); } final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event); final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); message.setMessageAnnotations(messageAnnotations); messages.add(message); } final Context finalSharedContext = sharedContext != null ? sharedContext : Context.NONE; return withRetry( getSendLink().flatMap(link -> { if (isTracingEnabled) { Context entityContext = finalSharedContext.addData(ENTITY_PATH_KEY, link.getEntityPath()); parentContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME_KEY, link.getHostname()), ProcessKind.SEND)); } return messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages); }) .doOnEach(signal -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), signal); } }) .doOnError(error -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), Signal.error(error)); } }), retryOptions.getTryTimeout(), retryPolicy); } /** * Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is * enqueued and made available to receivers only at the scheduled enqueue time. * * @param message Message to be sent to the Service Bus Queue. * @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic. * * @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message. * * @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}. */ /** * Cancels the enqueuing of an already scheduled message, if it was not already enqueued. * * @param sequenceNumber of the scheduled message to cancel. * * @return The {@link Mono} that finishes this operation on service bus resource. */ public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName)) .flatMap(x -> x.cancelSchedule(sequenceNumber)); } /** * Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } connectionProcessor.dispose(); } private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages) { return getSendLink() .flatMap(link -> link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final CreateBatchOptions batchOptions = new CreateBatchOptions() .setMaximumSizeInBytes(batchSize); return messages.collect(new AmqpMessageCollector(batchOptions, 1, link::getErrorContext, tracerProvider, messageSerializer)); }) .flatMap(list -> sendInternalBatch(Flux.fromIterable(list)))); } private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private Mono<AmqpSendLink> getSendLink() { final String entityPath = entityName; final String linkName = entityName; return connectionProcessor .flatMap(connection -> connection.createSendLink(linkName, entityPath, retryOptions)); } private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> { private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private final TracerProvider tracerProvider; private final MessageSerializer serializer; private volatile ServiceBusMessageBatch currentBatch; AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.contextProvider = contextProvider; this.tracerProvider = tracerProvider; this.serializer = serializer; currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); } @Override public Supplier<List<ServiceBusMessageBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() { return (list, event) -> { ServiceBusMessageBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<ServiceBusMessageBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() { return list -> { ServiceBusMessageBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
class ServiceBusSenderAsyncClient implements AutoCloseable { /** * The default maximum allowable size, in bytes, for a batch to be sent. */ static final int MAX_MESSAGE_LENGTH_BYTES = 256 * 1024; private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions(); private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final AmqpRetryOptions retryOptions; private final AmqpRetryPolicy retryPolicy; private final MessagingEntityType entityType; private final Runnable onClientClose; private final String entityName; private final ServiceBusConnectionProcessor connectionProcessor; /** * Creates a new instance of this {@link ServiceBusSenderAsyncClient} that sends messages to a Service Bus entity. */ ServiceBusSenderAsyncClient(String entityName, MessagingEntityType entityType, ServiceBusConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider, MessageSerializer messageSerializer, Runnable onClientClose) { this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); this.entityName = Objects.requireNonNull(entityName, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = tracerProvider; this.retryPolicy = getRetryPolicy(retryOptions); this.entityType = entityType; this.onClientClose = onClientClose; } /** * Gets the fully qualified namespace. * * @return The fully qualified namespace. */ public String getFullyQualifiedNamespace() { return connectionProcessor.getFullyQualifiedNamespace(); } /** * Gets the name of the Service Bus resource. * * @return The name of the Service Bus resource. */ public String getEntityPath() { return entityName; } /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * * @return The {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); return sendInternal(Flux.just(message)); } /** * Sends a message to a Service Bus queue or topic. * * @param message Message to be sent to Service Bus queue or topic. * @param sessionId the session id to associate with the message. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code message} or {@code sessionId} is {@code null}. */ public Mono<Void> send(ServiceBusMessage message, String sessionId) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(sessionId, "'sessionId' cannot be null."); return Mono.error(new IllegalStateException("Not implemented.")); } /** * Creates a {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows. * * @return A {@link ServiceBusMessageBatch} that can fit as many messages as the transport allows. */ public Mono<ServiceBusMessageBatch> createBatch() { return createBatch(DEFAULT_BATCH_OPTIONS); } /** * Creates an {@link ServiceBusMessageBatch} configured with the options specified. * * @param options A set of options used to configure the {@link ServiceBusMessageBatch}. * @return A new {@link ServiceBusMessageBatch} configured with the given options. * @throws NullPointerException if {@code options} is null. */ public Mono<ServiceBusMessageBatch> createBatch(CreateBatchOptions options) { Objects.requireNonNull(options, "'options' cannot be null."); final int maxSize = options.getMaximumSizeInBytes(); return getSendLink().flatMap(link -> link.getLinkSize().flatMap(size -> { final int maximumLinkSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; if (maxSize > maximumLinkSize) { return monoError(logger, new IllegalArgumentException(String.format(Locale.US, "CreateBatchOptions.getMaximumSizeInBytes (%s bytes) is larger than the link size" + " (%s bytes).", maxSize, maximumLinkSize))); } final int batchSize = maxSize > 0 ? maxSize : maximumLinkSize; return Mono.just( new ServiceBusMessageBatch(batchSize, link::getErrorContext, tracerProvider, messageSerializer)); })); } /** * Sends a message batch to the Azure Service Bus entity this sender is connected to. * * @param batch of messages which allows client to send maximum allowed size for a batch of messages. * * @return A {@link Mono} the finishes this operation on service bus resource. * * @throws NullPointerException if {@code batch} is {@code null}. */ public Mono<Void> send(ServiceBusMessageBatch batch) { Objects.requireNonNull(batch, "'batch' cannot be null."); final boolean isTracingEnabled = tracerProvider.isEnabled(); final AtomicReference<Context> parentContext = isTracingEnabled ? new AtomicReference<>(Context.NONE) : null; if (batch.getMessages().isEmpty()) { logger.info("Cannot send an EventBatch that is empty."); return Mono.empty(); } logger.info("Sending batch with size[{}].", batch.getCount()); Context sharedContext = null; final List<org.apache.qpid.proton.message.Message> messages = new ArrayList<>(); for (int i = 0; i < batch.getMessages().size(); i++) { final ServiceBusMessage event = batch.getMessages().get(i); if (isTracingEnabled) { parentContext.set(event.getContext()); if (i == 0) { sharedContext = tracerProvider.getSharedSpanBuilder(parentContext.get()); } tracerProvider.addSpanLinks(sharedContext.addData(SPAN_CONTEXT_KEY, event.getContext())); } final org.apache.qpid.proton.message.Message message = messageSerializer.serialize(event); final MessageAnnotations messageAnnotations = message.getMessageAnnotations() == null ? new MessageAnnotations(new HashMap<>()) : message.getMessageAnnotations(); message.setMessageAnnotations(messageAnnotations); messages.add(message); } final Context finalSharedContext = sharedContext != null ? sharedContext : Context.NONE; return withRetry( getSendLink().flatMap(link -> { if (isTracingEnabled) { Context entityContext = finalSharedContext.addData(ENTITY_PATH_KEY, link.getEntityPath()); parentContext.set(tracerProvider.startSpan( entityContext.addData(HOST_NAME_KEY, link.getHostname()), ProcessKind.SEND)); } return messages.size() == 1 ? link.send(messages.get(0)) : link.send(messages); }) .doOnEach(signal -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), signal); } }) .doOnError(error -> { if (isTracingEnabled) { tracerProvider.endSpan(parentContext.get(), Signal.error(error)); } }), retryOptions.getTryTimeout(), retryPolicy); } /** * Sends a scheduled message to the Azure Service Bus entity this sender is connected to. A scheduled message is * enqueued and made available to receivers only at the scheduled enqueue time. * * @param message Message to be sent to the Service Bus Queue. * @param scheduledEnqueueTime Instant at which the message should appear in the Service Bus queue or topic. * * @return The sequence number of the scheduled message which can be used to cancel the scheduling of the message. * * @throws NullPointerException if {@code message} or {@code scheduledEnqueueTime} is {@code null}. */ /** * Cancels the enqueuing of an already scheduled message, if it was not already enqueued. * * @param sequenceNumber of the scheduled message to cancel. * * @return The {@link Mono} that finishes this operation on service bus resource. */ public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityName, entityType)) .flatMap(managementNode -> managementNode.cancelScheduledMessage(sequenceNumber)); } /** * Disposes of the {@link ServiceBusSenderAsyncClient}. If the client had a dedicated connection, the underlying * connection is also closed. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } onClientClose.run(); } private Mono<Void> sendInternal(Flux<ServiceBusMessage> messages) { return getSendLink() .flatMap(link -> link.getLinkSize() .flatMap(size -> { final int batchSize = size > 0 ? size : MAX_MESSAGE_LENGTH_BYTES; final CreateBatchOptions batchOptions = new CreateBatchOptions() .setMaximumSizeInBytes(batchSize); return messages.collect(new AmqpMessageCollector(batchOptions, 1, link::getErrorContext, tracerProvider, messageSerializer)); }) .flatMap(list -> sendInternalBatch(Flux.fromIterable(list)))); } private Mono<Void> sendInternalBatch(Flux<ServiceBusMessageBatch> eventBatches) { return eventBatches .flatMap(this::send) .then() .doOnError(error -> { logger.error("Error sending batch.", error); }); } private Mono<AmqpSendLink> getSendLink() { return connectionProcessor .flatMap(connection -> connection.createSendLink(entityName, entityName, retryOptions)); } private static class AmqpMessageCollector implements Collector<ServiceBusMessage, List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> { private final int maxMessageSize; private final Integer maxNumberOfBatches; private final ErrorContextProvider contextProvider; private final TracerProvider tracerProvider; private final MessageSerializer serializer; private volatile ServiceBusMessageBatch currentBatch; AmqpMessageCollector(CreateBatchOptions options, Integer maxNumberOfBatches, ErrorContextProvider contextProvider, TracerProvider tracerProvider, MessageSerializer serializer) { this.maxNumberOfBatches = maxNumberOfBatches; this.maxMessageSize = options.getMaximumSizeInBytes() > 0 ? options.getMaximumSizeInBytes() : MAX_MESSAGE_LENGTH_BYTES; this.contextProvider = contextProvider; this.tracerProvider = tracerProvider; this.serializer = serializer; currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); } @Override public Supplier<List<ServiceBusMessageBatch>> supplier() { return ArrayList::new; } @Override public BiConsumer<List<ServiceBusMessageBatch>, ServiceBusMessage> accumulator() { return (list, event) -> { ServiceBusMessageBatch batch = currentBatch; if (batch.tryAdd(event)) { return; } if (maxNumberOfBatches != null && list.size() == maxNumberOfBatches) { final String message = String.format(Locale.US, "EventData does not fit into maximum number of batches. '%s'", maxNumberOfBatches); throw new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, message, contextProvider.getErrorContext()); } currentBatch = new ServiceBusMessageBatch(maxMessageSize, contextProvider, tracerProvider, serializer); currentBatch.tryAdd(event); list.add(batch); }; } @Override public BinaryOperator<List<ServiceBusMessageBatch>> combiner() { return (existing, another) -> { existing.addAll(another); return existing; }; } @Override public Function<List<ServiceBusMessageBatch>, List<ServiceBusMessageBatch>> finisher() { return list -> { ServiceBusMessageBatch batch = currentBatch; currentBatch = null; if (batch != null) { list.add(batch); } return list; }; } @Override public Set<Characteristics> characteristics() { return Collections.emptySet(); } } }
Its more specific you to create a mock of the message and then if the managementNode gets a schedule call with that instance to return the number. any() should be used in the case when the parameter can be variable things or its not specific to the test case you are checking.
void scheduleMessage() { long sequenceNumberReturned =10; when(managementNode.schedule(any(ServiceBusMessage.class), any(Instant.class))) .thenReturn(just(sequenceNumberReturned)); StepVerifier.create(sender.scheduleMessage(mock(ServiceBusMessage.class), mock(Instant.class))) .expectNext(sequenceNumberReturned) .verifyComplete(); }
StepVerifier.create(sender.scheduleMessage(mock(ServiceBusMessage.class), mock(Instant.class)))
void scheduleMessage() { long sequenceNumberReturned = 10; Instant instant = mock(Instant.class); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), any(AmqpRetryOptions.class))) .thenReturn(Mono.just(sendLink)); when(sendLink.getLinkSize()).thenReturn(Mono.just(MAX_MESSAGE_LENGTH_BYTES)); when(managementNode.schedule(eq(message), eq(instant), any(Integer.class))) .thenReturn(just(sequenceNumberReturned)); StepVerifier.create(sender.scheduleMessage(message, instant)) .expectNext(sequenceNumberReturned) .verifyComplete(); verify(managementNode).schedule(message, instant, MAX_MESSAGE_LENGTH_BYTES); }
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorContextProvider errorContextProvider; @Mock private ServiceBusManagementNode managementNode; @Captor private ArgumentCaptor<org.apache.qpid.proton.message.Message> singleMessageCaptor; @Captor private ArgumentCaptor<List<org.apache.qpid.proton.message.Message>> messagesCaptor; private MessageSerializer serializer = new ServiceBusMessageSerializer(); private TracerProvider tracerProvider = new TracerProvider(Collections.emptyList()); private final ClientLogger logger = new ClientLogger(ServiceBusSenderAsyncClient.class); private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer(); private final AmqpRetryOptions retryOptions = new AmqpRetryOptions() .setDelay(Duration.ofMillis(500)) .setMode(AmqpRetryMode.FIXED) .setTryTimeout(Duration.ofSeconds(10)); private final DirectProcessor<AmqpEndpointState> endpointProcessor = DirectProcessor.create(); private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private ServiceBusSenderAsyncClient sender; private ServiceBusConnectionProcessor connectionProcessor; private ConnectionOptions connectionOptions; private static final String TEST_CONTENTS = "My message for service bus queue!"; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup() { MockitoAnnotations.initMocks(this); tracerProvider = new TracerProvider(Collections.emptyList()); connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, retryOptions, ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); when(connection.getEndpointStates()).thenReturn(endpointProcessor); endpointSink.next(AmqpEndpointState.ACTIVE); connectionProcessor = Mono.fromCallable(() -> connection).repeat(10).subscribeWith( new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), ENTITY_NAME, connectionOptions.getRetry())); sender = new ServiceBusSenderAsyncClient(ENTITY_NAME, connectionProcessor, retryOptions, tracerProvider, messageSerializer); when(connection.getManagementNode(anyString())).thenReturn(just(managementNode)); when(sendLink.getLinkSize()).thenReturn(Mono.just(ServiceBusSenderAsyncClient.MAX_MESSAGE_LENGTH_BYTES)); } @AfterEach void teardown() { Mockito.framework().clearInlineMocks(); sendLink = null; connection = null; singleMessageCaptor = null; messagesCaptor = null; } /** * Verifies that sending multiple message will result in calling sender.send(MessageBatch). */ @Test void sendMultipleMessages() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessageBatch batch = new ServiceBusMessageBatch(256 * 1024, errorContextProvider, tracerProvider, serializer); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); Assertions.assertTrue(batch.tryAdd(message)); }); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(any(Message.class))).thenReturn(Mono.empty()); when(sendLink.send(anyList())).thenReturn(Mono.empty()); StepVerifier.create(sender.send(batch)) .verifyComplete(); verify(sendLink).send(messagesCaptor.capture()); final List<org.apache.qpid.proton.message.Message> messagesSent = messagesCaptor.getValue(); Assertions.assertEquals(count, messagesSent.size()); messagesSent.forEach(message -> Assertions.assertEquals(Section.SectionType.Data, message.getBody().getType())); } /** * Verifies that sending a single message will result in calling sender.send(Message). */ @Test void sendSingleMessage() { final ServiceBusMessage testData = new ServiceBusMessage(TEST_CONTENTS.getBytes(UTF_8)); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(any(org.apache.qpid.proton.message.Message.class))).thenReturn(Mono.empty()); StepVerifier.create(sender.send(testData)) .verifyComplete(); verify(sendLink, times(1)).send(any(org.apache.qpid.proton.message.Message.class)); verify(sendLink).send(singleMessageCaptor.capture()); final Message message = singleMessageCaptor.getValue(); Assertions.assertEquals(Section.SectionType.Data, message.getBody().getType()); } @Test @Test void cancelScheduleMessage() { long sequenceNumberReturned =10; when(managementNode.cancelSchedule(any(Long.class))) .thenReturn(Mono.empty()); StepVerifier.create(sender.cancelScheduledMessage(sequenceNumberReturned)) .verifyComplete(); } }
class ServiceBusSenderAsyncClientTest { private static final String NAMESPACE = "my-namespace"; private static final String ENTITY_NAME = "my-servicebus-entity"; @Mock private AmqpSendLink sendLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private ErrorContextProvider errorContextProvider; @Mock private ServiceBusManagementNode managementNode; @Mock private ServiceBusMessage message; @Mock private Runnable onClientClose; @Captor private ArgumentCaptor<org.apache.qpid.proton.message.Message> singleMessageCaptor; @Captor private ArgumentCaptor<List<org.apache.qpid.proton.message.Message>> messagesCaptor; private MessageSerializer serializer = new ServiceBusMessageSerializer(); private TracerProvider tracerProvider = new TracerProvider(Collections.emptyList()); private final MessageSerializer messageSerializer = new ServiceBusMessageSerializer(); private final AmqpRetryOptions retryOptions = new AmqpRetryOptions() .setDelay(Duration.ofMillis(500)) .setMode(AmqpRetryMode.FIXED) .setTryTimeout(Duration.ofSeconds(10)); private final DirectProcessor<AmqpEndpointState> endpointProcessor = DirectProcessor.create(); private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private ServiceBusSenderAsyncClient sender; private ServiceBusConnectionProcessor connectionProcessor; private ConnectionOptions connectionOptions; private static final String TEST_CONTENTS = "My message for service bus queue!"; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(30)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup() { MockitoAnnotations.initMocks(this); tracerProvider = new TracerProvider(Collections.emptyList()); connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, retryOptions, ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); when(connection.getEndpointStates()).thenReturn(endpointProcessor); endpointSink.next(AmqpEndpointState.ACTIVE); connectionProcessor = Mono.fromCallable(() -> connection).repeat(10).subscribeWith( new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getRetry())); sender = new ServiceBusSenderAsyncClient(ENTITY_NAME, MessagingEntityType.QUEUE, connectionProcessor, retryOptions, tracerProvider, messageSerializer, onClientClose); when(connection.getManagementNode(anyString(), any(MessagingEntityType.class))) .thenReturn(just(managementNode)); when(sendLink.getLinkSize()).thenReturn(Mono.just(ServiceBusSenderAsyncClient.MAX_MESSAGE_LENGTH_BYTES)); doNothing().when(onClientClose).run(); } @AfterEach void teardown() { Mockito.framework().clearInlineMocks(); sendLink = null; connection = null; singleMessageCaptor = null; messagesCaptor = null; } /** * Verifies that the correct Service Bus properties are set. */ @Test void verifyProperties() { Assertions.assertEquals(ENTITY_NAME, sender.getEntityPath()); Assertions.assertEquals(NAMESPACE, sender.getFullyQualifiedNamespace()); } /** * Verifies that an exception is thrown when we create a batch with null options. */ @Test void createBatchNull() { Assertions.assertThrows(NullPointerException.class, () -> sender.createBatch(null)); } /** * Verifies that the default batch is the same size as the message link. */ @Test void createBatchDefault() { when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), any(AmqpRetryOptions.class))) .thenReturn(Mono.just(sendLink)); when(sendLink.getLinkSize()).thenReturn(Mono.just(MAX_MESSAGE_LENGTH_BYTES)); StepVerifier.create(sender.createBatch()) .assertNext(batch -> { Assertions.assertEquals(MAX_MESSAGE_LENGTH_BYTES, batch.getMaxSizeInBytes()); Assertions.assertEquals(0, batch.getCount()); }) .verifyComplete(); } /** * Verifies we cannot create a batch if the options size is larger than the link. */ @Test void createBatchWhenSizeTooBig() { int maxLinkSize = 1024; int batchSize = maxLinkSize + 10; final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize); StepVerifier.create(sender.createBatch(options)) .expectError(IllegalArgumentException.class) .verify(); } /** * Verifies that the producer can create a batch with a given {@link CreateBatchOptions */ @Test void createsMessageBatchWithSize() { int maxLinkSize = 10000; int batchSize = 1024; int eventOverhead = 46; int maxEventPayload = batchSize - eventOverhead; final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); final ServiceBusMessage event = new ServiceBusMessage(new byte[maxEventPayload]); final ServiceBusMessage tooLargeEvent = new ServiceBusMessage(new byte[maxEventPayload + 1]); final CreateBatchOptions options = new CreateBatchOptions().setMaximumSizeInBytes(batchSize); StepVerifier.create(sender.createBatch(options)) .assertNext(batch -> { Assertions.assertEquals(batchSize, batch.getMaxSizeInBytes()); Assertions.assertTrue(batch.tryAdd(event)); }) .verifyComplete(); StepVerifier.create(sender.createBatch(options)) .assertNext(batch -> { Assertions.assertEquals(batchSize, batch.getMaxSizeInBytes()); Assertions.assertFalse(batch.tryAdd(tooLargeEvent)); }) .verifyComplete(); } /** * Verifies that sending multiple message will result in calling sender.send(MessageBatch). */ @Test void sendMultipleMessages() { final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); final ServiceBusMessageBatch batch = new ServiceBusMessageBatch(256 * 1024, errorContextProvider, tracerProvider, serializer); IntStream.range(0, count).forEach(index -> { final ServiceBusMessage message = new ServiceBusMessage(contents); Assertions.assertTrue(batch.tryAdd(message)); }); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(any(Message.class))).thenReturn(Mono.empty()); when(sendLink.send(anyList())).thenReturn(Mono.empty()); StepVerifier.create(sender.send(batch)) .verifyComplete(); verify(sendLink).send(messagesCaptor.capture()); final List<org.apache.qpid.proton.message.Message> messagesSent = messagesCaptor.getValue(); Assertions.assertEquals(count, messagesSent.size()); messagesSent.forEach(message -> Assertions.assertEquals(Section.SectionType.Data, message.getBody().getType())); } /** * Verifies that sending a single message will result in calling sender.send(Message). */ @Test void sendSingleMessage() { final ServiceBusMessage testData = new ServiceBusMessage(TEST_CONTENTS.getBytes(UTF_8)); when(connection.createSendLink(eq(ENTITY_NAME), eq(ENTITY_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.getLinkSize()).thenReturn(Mono.just(MAX_MESSAGE_LENGTH_BYTES)); when(sendLink.send(any(org.apache.qpid.proton.message.Message.class))).thenReturn(Mono.empty()); StepVerifier.create(sender.send(testData)) .verifyComplete(); verify(sendLink, times(1)).send(any(org.apache.qpid.proton.message.Message.class)); verify(sendLink).send(singleMessageCaptor.capture()); final Message message = singleMessageCaptor.getValue(); Assertions.assertEquals(Section.SectionType.Data, message.getBody().getType()); } @Test @Test void cancelScheduleMessage() { long sequenceNumberReturned = 10; when(managementNode.cancelScheduledMessage(eq(sequenceNumberReturned))).thenReturn(Mono.empty()); StepVerifier.create(sender.cancelScheduledMessage(sequenceNumberReturned)) .verifyComplete(); verify(managementNode).cancelScheduledMessage(sequenceNumberReturned); } /** * Verifies that the onClientClose is called. */ @Test void callsClientClose() { sender.close(); verify(onClientClose).run(); } /** * Verifies that the onClientClose is only called once. */ @Test void callsClientCloseOnce() { sender.close(); sender.close(); verify(onClientClose).run(); } }
I should have noticed it before, put the private `renewMessageLock` method into the public one. It is only used in one place. It saves another stack call.
private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; }
return message;
private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next(); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelSchedule(long sequenceNumber) { return cancelSchedule(new Long[]{sequenceNumber}); } /** * {@inheritDoc} */ @Override public Mono<Long> schedule(ServiceBusMessage message, Instant scheduledEnqueueTime) { return scheduleMessage(message, scheduledEnqueueTime) .next(); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ /*** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule) { int maxMessageSize = MAX_MESSAGE_LENGTH_SENDER_LINK_BYTES; Map<String, Object> requestBodyMap = new HashMap<>(); List<Message> messagesToSchedule = new ArrayList<>(); messagesToSchedule.add(messageSerializer.serialize(messageToSchedule)); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); for (Message message : messagesToSchedule) { final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); messageList.add(messageEntry); } requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } private Mono<Void> cancelSchedule(Long[] cancelScheduleNumbers) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, cancelScheduleNumbers))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel schedule message with sequence " + Arrays.toString(cancelScheduleNumbers), getErrorContext())); })).then(); } private Flux<Long> scheduleMessage(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap; requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not schedule message.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Long.class)); })); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return isAuthorized(PEEK_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, new UUID[]{lockToken}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not renew the lock for lock token: '%s'.", lockToken.toString()), getErrorContext())); } List<Instant> renewTimeList = messageSerializer.deserializeList(responseMessage, Instant.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. " + "Could not renew message with lock token: '%s'.", lockToken.toString()), getErrorContext())); } return renewTimeList.get(0); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ /** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @param maxMessageSize The maximum size allowed on send link. * * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule, int maxMessageSize) { Message message = messageSerializer.serialize(messageToSchedule); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); messageList.add(messageEntry); Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, new Long[]{sequenceNumber}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel scheduled message with sequence number " + sequenceNumber, getErrorContext())); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Long> schedule(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime, int maxSendLinkSize) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule, maxSendLinkSize); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } List<Long> sequenceNumberList = messageSerializer.deserializeList(responseMessage, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumberList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } return sequenceNumberList.get(0); })); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
is this what they do in track 1? update the actual parameter object itself? Since we want to make ServicebusReceivedMessage immutable, id expect a clone to be created.
public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage receivedMessage) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(receivedMessage.getLockToken()) .map(instant -> { receivedMessage.setLockedUntil(instant); return instant; })); }
receivedMessage.setLockedUntil(instant);
public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage receivedMessage) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(receivedMessage.getLockToken()) .map(instant -> { receivedMessage.setLockedUntil(instant); return instant; })); }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Autocomplete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param messageLock The {@link UUID} value of the message lock to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Instant> renewMessageLock(UUID messageLock) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(messageLock)); } /** * Asynchronously renews the lock on the specified message. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param receivedMessage to be used to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param fromSequenceNumber The sequence number from where to read the message. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages, fromSequenceNumber)); } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Autocomplete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param messageLock The {@link UUID} value of the message lock to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Instant> renewMessageLock(UUID messageLock) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(messageLock)); } /** * Asynchronously renews the lock on the specified message. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param receivedMessage to be used to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param fromSequenceNumber The sequence number from where to read the message. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages, fromSequenceNumber)); } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
I was thinking of when we have to renew multiple lock Token in one go and need to expose that API, this would be helpful. But for now I have changed this like you said.
private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; }
return message;
private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next(); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelSchedule(long sequenceNumber) { return cancelSchedule(new Long[]{sequenceNumber}); } /** * {@inheritDoc} */ @Override public Mono<Long> schedule(ServiceBusMessage message, Instant scheduledEnqueueTime) { return scheduleMessage(message, scheduledEnqueueTime) .next(); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ /*** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule) { int maxMessageSize = MAX_MESSAGE_LENGTH_SENDER_LINK_BYTES; Map<String, Object> requestBodyMap = new HashMap<>(); List<Message> messagesToSchedule = new ArrayList<>(); messagesToSchedule.add(messageSerializer.serialize(messageToSchedule)); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); for (Message message : messagesToSchedule) { final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); messageList.add(messageEntry); } requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } private Mono<Void> cancelSchedule(Long[] cancelScheduleNumbers) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, cancelScheduleNumbers))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel schedule message with sequence " + Arrays.toString(cancelScheduleNumbers), getErrorContext())); })).then(); } private Flux<Long> scheduleMessage(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap; requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not schedule message.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Long.class)); })); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return isAuthorized(PEEK_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, new UUID[]{lockToken}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not renew the lock for lock token: '%s'.", lockToken.toString()), getErrorContext())); } List<Instant> renewTimeList = messageSerializer.deserializeList(responseMessage, Instant.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. " + "Could not renew message with lock token: '%s'.", lockToken.toString()), getErrorContext())); } return renewTimeList.get(0); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ /** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @param maxMessageSize The maximum size allowed on send link. * * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule, int maxMessageSize) { Message message = messageSerializer.serialize(messageToSchedule); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); messageList.add(messageEntry); Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, new Long[]{sequenceNumber}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel scheduled message with sequence number " + sequenceNumber, getErrorContext())); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Long> schedule(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime, int maxSendLinkSize) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule, maxSendLinkSize); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } List<Long> sequenceNumberList = messageSerializer.deserializeList(responseMessage, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumberList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } return sequenceNumberList.get(0); })); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
Nothing is this code is async, you can use .map.
public Mono<Instant> renewMessageLock(UUID lockToken) { return isAuthorized(PEEK_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, new UUID[]{lockToken}))); return channel.sendWithAck(requestMessage); }).flatMap(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } List<Instant> renewTimeList = messageSerializer.deserializeList(responseMessage, Instant.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. " + "Could not renew message with lock token: '%s'.", lockToken.toString()), getErrorContext()))); } return Mono.just(renewTimeList.get(0)); })); }
}).flatMap(responseMessage -> {
public Mono<Instant> renewMessageLock(UUID lockToken) { return isAuthorized(PEEK_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, new UUID[]{lockToken}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not renew the lock for lock token: '%s'.", lockToken.toString()), getErrorContext())); } List<Instant> renewTimeList = messageSerializer.deserializeList(responseMessage, Instant.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. " + "Could not renew message with lock token: '%s'.", lockToken.toString()), getErrorContext())); } return renewTimeList.get(0); })); }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * {@inheritDoc} */ @Override /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } /** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @param maxMessageSize The maximum size allowed on send link. * * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule, int maxMessageSize) { Message message = messageSerializer.serialize(messageToSchedule); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); messageList.add(messageEntry); Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, new Long[]{sequenceNumber}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel scheduled message with sequence number " + sequenceNumber, getErrorContext())); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Long> schedule(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime, int maxSendLinkSize) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule, maxSendLinkSize); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).flatMap(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format("Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext()))); } List<Long> sequenceNumberList = messageSerializer.deserializeList(responseMessage, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumberList)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext()))); } return Mono.just(sequenceNumberList.get(0)); })); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * {@inheritDoc} */ @Override /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } /** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @param maxMessageSize The maximum size allowed on send link. * * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule, int maxMessageSize) { Message message = messageSerializer.serialize(messageToSchedule); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); messageList.add(messageEntry); Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, new Long[]{sequenceNumber}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel scheduled message with sequence number " + sequenceNumber, getErrorContext())); })).then(); } /** * {@inheritDoc} */ @Override public Mono<Long> schedule(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime, int maxSendLinkSize) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule, maxSendLinkSize); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } List<Long> sequenceNumberList = messageSerializer.deserializeList(responseMessage, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumberList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } return sequenceNumberList.get(0); })); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
Similar to my first comment above. This can be .map rather than .flatMap.
public Mono<Long> schedule(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime, int maxSendLinkSize) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule, maxSendLinkSize); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).flatMap(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format("Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext()))); } List<Long> sequenceNumberList = messageSerializer.deserializeList(responseMessage, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumberList)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext()))); } return Mono.just(sequenceNumberList.get(0)); })); }
}).flatMap(responseMessage -> {
public Mono<Long> schedule(ServiceBusMessage messageToSchedule, Instant scheduledEnqueueTime, int maxSendLinkSize) { messageToSchedule.setScheduledEnqueueTime(scheduledEnqueueTime); return isAuthorized(SCHEDULE_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(SCHEDULE_MESSAGE_OPERATION, channel.getReceiveLinkName()); Map<String, Object> requestBodyMap = createScheduleMessgeAmqpValue(messageToSchedule, maxSendLinkSize); requestMessage.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } List<Long> sequenceNumberList = messageSerializer.deserializeList(responseMessage, Long.class); if (CoreUtils.isNullOrEmpty(sequenceNumberList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. Could not schedule message with message id: '%s'.", messageToSchedule.getMessageId()), getErrorContext())); } return sequenceNumberList.get(0); })); }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return isAuthorized(PEEK_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, new UUID[]{lockToken}))); return channel.sendWithAck(requestMessage); }).flatMap(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } List<Instant> renewTimeList = messageSerializer.deserializeList(responseMessage, Instant.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. " + "Could not renew message with lock token: '%s'.", lockToken.toString()), getErrorContext()))); } return Mono.just(renewTimeList.get(0)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } /** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @param maxMessageSize The maximum size allowed on send link. * * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule, int maxMessageSize) { Message message = messageSerializer.serialize(messageToSchedule); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); messageList.add(messageEntry); Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, new Long[]{sequenceNumber}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel scheduled message with sequence number " + sequenceNumber, getErrorContext())); })).then(); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(ReceiveMode receiveMode, long sequenceNumber) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumber) .next(); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, long... sequenceNumbers) { return receiveDeferredMessageBatch(receiveMode, null, sequenceNumbers); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION, channel.getReceiveLinkName()); final HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Flux<ServiceBusReceivedMessage> receiveDeferredMessageBatch(ReceiveMode receiveMode, UUID sessionId, long... fromSequenceNumbers) { return isAuthorized(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(RECEIVE_BY_SEQUENCE_NUMBER_OPERATION, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(SEQUENCE_NUMBERS, Arrays.stream(fromSequenceNumbers) .boxed().toArray(Long[]::new)); requestBodyMap.put(RECEIVER_SETTLE_MODE, UnsignedInteger.valueOf(receiveMode == ReceiveMode.RECEIVE_AND_DELETE ? 0 : 1)); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return isAuthorized(PEEK_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS_KEY, new UUID[]{lockToken}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Could not renew the lock for lock token: '%s'.", lockToken.toString()), getErrorContext())); } List<Instant> renewTimeList = messageSerializer.deserializeList(responseMessage, Instant.class); if (CoreUtils.isNullOrEmpty(renewTimeList)) { throw logger.logExceptionAsError(new AmqpException(false, String.format("Service bus response empty. " + "Could not renew message with lock token: '%s'.", lockToken.toString()), getErrorContext())); } return renewTimeList.get(0); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } /** * Create a Amqp key, value map to be used to create Amqp mesage for scheduling purpose. * * @param messageToSchedule The message which needs to be scheduled. * @param maxMessageSize The maximum size allowed on send link. * * @return Map of key and value in Amqp format. * @throws AmqpException When payload exceeded maximum message allowed size. */ private Map<String, Object> createScheduleMessgeAmqpValue(ServiceBusMessage messageToSchedule, int maxMessageSize) { Message message = messageSerializer.serialize(messageToSchedule); final int payloadSize = messageSerializer.getSize(message); final int allocationSize = Math.min(payloadSize + MAX_MESSAGING_AMQP_HEADER_SIZE_BYTES, maxMessageSize); final byte[] bytes = new byte[allocationSize]; int encodedSize; try { encodedSize = message.encode(bytes, 0, allocationSize); } catch (BufferOverflowException exception) { final String errorMessage = String.format(Locale.US, "Error sending. Size of the payload exceeded maximum message size: %s kb", maxMessageSize / 1024); throw logger.logExceptionAsWarning(new AmqpException(false, AmqpErrorCondition.LINK_PAYLOAD_SIZE_EXCEEDED, errorMessage, exception, getErrorContext())); } HashMap<String, Object> messageEntry = new HashMap<>(); messageEntry.put(MESSAGE, new Binary(bytes, 0, encodedSize)); messageEntry.put(MESSAGE_ID, message.getMessageId()); Collection<HashMap<String, Object>> messageList = new LinkedList<>(); messageList.add(messageEntry); Map<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(MESSAGES, messageList); return requestBodyMap; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public Mono<Void> cancelScheduledMessage(long sequenceNumber) { return isAuthorized(CANCEL_SCHEDULED_MESSAGE_OPERATION).then(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(CANCEL_SCHEDULED_MESSAGE_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(SEQUENCE_NUMBERS, new Long[]{sequenceNumber}))); return channel.sendWithAck(requestMessage); }).map(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode == AmqpResponseCode.OK.getValue()) { return Mono.empty(); } return Mono.error(new AmqpException(false, "Could not cancel scheduled message with sequence number " + sequenceNumber, getErrorContext())); })).then(); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
nit: remove System.out
void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); System.out.println("Completed."); }
System.out.println("Completed.");
void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } }
Do you have test when user do not want autoComplete and want to call him self ?
public Mono<Void> complete(ServiceBusReceivedMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException( "Complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).then( connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.complete(message.getLockToken())) .then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken())))); }
if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) {
public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Auto-complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive().map(message -> { if (!MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); } return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return null; } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Instant renewMessageLock(ServiceBusReceivedMessage message) { return null; } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@link ServiceBusReceiverAsyncClient * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * @param maxMessages to peek. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return null; } /** * @param maxMessages to peek. * @param fromSequenceNumber to peek message from. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return null; } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkMono.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Auto-complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Instant renewMessageLock(ServiceBusReceivedMessage message) { return null; } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * @param maxMessages to peek. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return null; } /** * @param maxMessages to peek. * @param fromSequenceNumber to peek message from. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return null; } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
I'll add that.
public Mono<Void> complete(ServiceBusReceivedMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException( "Complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).then( connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.complete(message.getLockToken())) .then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken())))); }
if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) {
public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Auto-complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive().map(message -> { if (!MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); } return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return null; } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Instant renewMessageLock(ServiceBusReceivedMessage message) { return null; } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@link ServiceBusReceiverAsyncClient * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * @param maxMessages to peek. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return null; } /** * @param maxMessages to peek. * @param fromSequenceNumber to peek message from. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return null; } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkMono.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Auto-complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Instant renewMessageLock(ServiceBusReceivedMessage message) { return null; } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * @param maxMessages to peek. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return null; } /** * @param maxMessages to peek. * @param fromSequenceNumber to peek message from. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return null; } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
Any reason this is called Mono when it is a Flux?
private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLinkMono = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLinkMono.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete); }); }
final Flux<AmqpReceiveLink> receiveLinkMono =
private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Auto-complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive().map(message -> { if (!MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); } return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return null; } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { Objects.requireNonNull(message, "'message' cannot be null."); if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException( "Complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).then( connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.complete(message.getLockToken())) .then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken())))); } /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return null; } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return null; } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Instant renewMessageLock(ServiceBusReceivedMessage message) { return null; } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@link ServiceBusReceiverAsyncClient * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * @param maxMessages to peek. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return null; } /** * @param maxMessages to peek. * @param fromSequenceNumber to peek message from. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return null; } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Auto-complete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Instant renewMessageLock(ServiceBusReceivedMessage message) { return null; } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * @param maxMessages to peek. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return null; } /** * @param maxMessages to peek. * @param fromSequenceNumber to peek message from. * * @return Flux of {@link ServiceBusReceivedMessage}. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return null; } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
Try Mono.when(sender.send(message), sender.send(message))
void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(sender.send(message) .then(sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); }
StepVerifier.create(sender.send(message)
void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); Assertions.assertEquals(messageId, receivedMessage.getProperties().get(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); Assertions.assertEquals(messageId, receivedMessage.getProperties().get(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequencenumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); Assertions.assertEquals(messageId, receivedMessage.getProperties().get(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(sender.send(message) .then(sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test }
Instead of asserting the number of events, I would try to assert that the messages I expect came back. (ie. message 1 and message 2)
void peekBatchWithSequenceNumberMessages() { final int numberOfEvents = 2; final int fromSequenceNumber = 10; when(managementNode.peekBatch(numberOfEvents, fromSequenceNumber)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{message1, message2})); StepVerifier.create(consumer.peekBatch(numberOfEvents, fromSequenceNumber)) .expectNextCount(numberOfEvents) .verifyComplete(); }
StepVerifier.create(consumer.peekBatch(numberOfEvents, fromSequenceNumber))
void peekBatchWithSequenceNumberMessages() { final int numberOfEvents = 2; final int fromSequenceNumber = 10; when(managementNode.peekBatch(numberOfEvents, fromSequenceNumber)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(consumer.peekBatch(numberOfEvents, fromSequenceNumber)) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); }
class ServiceBusReceiverAsyncClientTest { private static final String PAYLOAD = "hello"; private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8); private static final int PREFETCH = 5; private static final String NAMESPACE = "my-namespace-foo"; private static final String ENTITY_NAME = "queue-name"; private final String messageTrackingUUID = UUID.randomUUID().toString(); private final DirectProcessor<AmqpEndpointState> endpointProcessor = DirectProcessor.create(); private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private final DirectProcessor<Message> messageProcessor = DirectProcessor.create(); @Mock private AmqpReceiveLink amqpReceiveLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private MessageSerializer messageSerializer; @Mock private TracerProvider tracerProvider; @Mock private ServiceBusManagementNode managementNode; @Mock private ServiceBusReceivedMessage message1; @Mock private ServiceBusReceivedMessage message2; private ServiceBusReceiverAsyncClient consumer; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(10)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup() { MockitoAnnotations.initMocks(this); when(amqpReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single())); when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); when(messageSerializer.deserialize(any(), argThat(ServiceBusReceivedMessage.class::equals))) .thenAnswer(invocation -> { return mock(ServiceBusReceivedMessage.class); }); ConnectionOptions connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, new AmqpRetryOptions(), ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); when(connection.getEndpointStates()).thenReturn(endpointProcessor); endpointSink.next(AmqpEndpointState.ACTIVE); when(connection.createReceiveLink(anyString(), anyString(), any(ReceiveMode.class))).thenReturn(just(amqpReceiveLink)); when(connection.getManagementNode(anyString())).thenReturn(just(managementNode)); ServiceBusConnectionProcessor connectionProcessor = Flux.<ServiceBusAmqpConnection>create(sink -> sink.next(connection)) .subscribeWith(new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), ENTITY_NAME, connectionOptions.getRetry())); ReceiveMessageOptions receiveOptions = new ReceiveMessageOptions().setPrefetchCount(PREFETCH); consumer = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_NAME, connectionProcessor, tracerProvider, messageSerializer, receiveOptions); } @AfterEach void teardown() { Mockito.framework().clearInlineMocks(); consumer.close(); } /** * Verifies that when user calls peek more than one time, It returns different object. */ @SuppressWarnings("unchecked") @Test void peekTwoMessages() { /* Arrange */ final int numberOfEvents = 1; when(managementNode.peek()) .thenReturn(just(message1), just(message2)); StepVerifier.create(consumer.peek()) .expectNext(message1) .verifyComplete(); StepVerifier.create(consumer.peek()) .expectNext(message2) .verifyComplete(); } /** * Verifies that this peek one messages. */ @Test void peekOneMessage() { final int numberOfEvents = 1; when(managementNode.peek()) .thenReturn(just(mock(ServiceBusReceivedMessage.class))); StepVerifier.create(consumer.peek()) .expectNextCount(numberOfEvents) .verifyComplete(); } /** * Verifies that this peek one messages from a sequence Number. */ @Test void peekWithSequenceOneMessage() { final int numberOfEvents = 1; final int fromSequenceNumber = 10; when(managementNode.peek(fromSequenceNumber)) .thenReturn(just(mock(ServiceBusReceivedMessage.class))); StepVerifier.create(consumer.peek(fromSequenceNumber)) .expectNextCount(numberOfEvents) .verifyComplete(); } /** * Verifies that this receives a number of messages. Verifies that the initial credits we add are equal to the * prefetch value. */ @Test void receivesNumberOfEvents() { final int numberOfEvents = 1; StepVerifier.create(consumer.receive().take(numberOfEvents)) .then(() -> sendMessages(messageProcessor.sink(), numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink, times(1)).addCredits(PREFETCH); } /** * Verifies that this peek batch of messages. */ @Test void peekBatchMessages() { final int numberOfEvents = 2; when(managementNode.peekBatch(numberOfEvents)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{message1, message2})); StepVerifier.create(consumer.peekBatch(numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); } /** * Verifies that this peek batch of messages from a sequence Number. */ @Test private void sendMessages(FluxSink<Message> sink, int numberOfEvents) { Map<String, String> map = Collections.singletonMap("SAMPLE_HEADER", "foo"); for (int i = 0; i < numberOfEvents; i++) { Message message = getMessage(PAYLOAD_BYTES, messageTrackingUUID, map); sink.next(message); } } }
class ServiceBusReceiverAsyncClientTest { private static final String PAYLOAD = "hello"; private static final byte[] PAYLOAD_BYTES = PAYLOAD.getBytes(UTF_8); private static final int PREFETCH = 5; private static final String NAMESPACE = "my-namespace-foo"; private static final String ENTITY_PATH = "queue-name"; private static final MessagingEntityType ENTITY_TYPE = MessagingEntityType.QUEUE; private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClientTest.class); private final String messageTrackingUUID = UUID.randomUUID().toString(); private final DirectProcessor<AmqpEndpointState> endpointProcessor = DirectProcessor.create(); private final FluxSink<AmqpEndpointState> endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private final DirectProcessor<Message> messageProcessor = DirectProcessor.create(); private final FluxSink<Message> messageSink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private ServiceBusConnectionProcessor connectionProcessor; private ServiceBusReceiverAsyncClient consumer; private ReceiveMessageOptions receiveOptions; @Mock private AmqpReceiveLink amqpReceiveLink; @Mock private ServiceBusAmqpConnection connection; @Mock private TokenCredential tokenCredential; @Mock private MessageSerializer messageSerializer; @Mock private TracerProvider tracerProvider; @Mock private ServiceBusManagementNode managementNode; @Mock private ServiceBusReceivedMessage receivedMessage; @Mock private ServiceBusReceivedMessage receivedMessage2; @BeforeAll static void beforeAll() { StepVerifier.setDefaultTimeout(Duration.ofSeconds(100)); } @AfterAll static void afterAll() { StepVerifier.resetDefaultTimeout(); } @BeforeEach void setup(TestInfo testInfo) { String testName = testInfo.getTestMethod().isPresent() ? testInfo.getTestMethod().get().getName() : testInfo.getDisplayName(); logger.info("Running '{}'", testName); MockitoAnnotations.initMocks(this); when(amqpReceiveLink.receive()).thenReturn(messageProcessor.publishOn(Schedulers.single())); when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); ConnectionOptions connectionOptions = new ConnectionOptions(NAMESPACE, tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, new AmqpRetryOptions(), ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); when(connection.getEndpointStates()).thenReturn(endpointProcessor); endpointSink.next(AmqpEndpointState.ACTIVE); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode)); when(connection.createReceiveLink(anyString(), anyString(), any(ReceiveMode.class), anyBoolean(), any(), any(MessagingEntityType.class))).thenReturn(Mono.just(amqpReceiveLink)); connectionProcessor = Flux.<ServiceBusAmqpConnection>create(sink -> sink.next(connection)) .subscribeWith(new ServiceBusConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), ENTITY_PATH, connectionOptions.getRetry())); receiveOptions = new ReceiveMessageOptions().setPrefetchCount(PREFETCH); consumer = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, false, receiveOptions, connectionProcessor, tracerProvider, messageSerializer); } @AfterEach void teardown() { Mockito.framework().clearInlineMocks(); consumer.close(); } /** * Verifies that when user calls peek more than one time, It returns different object. */ @SuppressWarnings("unchecked") @Test void peekTwoMessages() { when(managementNode.peek()).thenReturn(Mono.just(receivedMessage), Mono.just(receivedMessage2)); StepVerifier.create(consumer.peek()) .expectNext(receivedMessage) .verifyComplete(); StepVerifier.create(consumer.peek()) .expectNext(receivedMessage2) .verifyComplete(); } /** * Verifies that this peek one messages from a sequence Number. */ @Test void peekWithSequenceOneMessage() { final int fromSequenceNumber = 10; final ServiceBusReceivedMessage receivedMessage = mock(ServiceBusReceivedMessage.class); when(managementNode.peek(fromSequenceNumber)).thenReturn(Mono.just(receivedMessage)); StepVerifier.create(consumer.peek(fromSequenceNumber)) .expectNext(receivedMessage) .verifyComplete(); } /** * Verifies that this receives a number of messages. Verifies that the initial credits we add are equal to the * prefetch value. */ @Test void receivesNumberOfEvents() { final int numberOfEvents = 1; final List<Message> messages = getMessages(10); when(messageSerializer.deserialize(any(Message.class), eq(ServiceBusReceivedMessage.class))) .thenReturn(mock(ServiceBusReceivedMessage.class)); StepVerifier.create(consumer.receive().take(numberOfEvents)) .then(() -> messages.forEach(m -> messageSink.next(m))) .expectNextCount(numberOfEvents) .verifyComplete(); verify(amqpReceiveLink).addCredits(PREFETCH); } /** * Verifies that we can receive messages from the processor. */ @Test void receivesAndAutoCompletes() { final ReceiveMessageOptions options = new ReceiveMessageOptions().setPrefetchCount(PREFETCH) .setAutoComplete(true); final ServiceBusReceiverAsyncClient consumer2 = new ServiceBusReceiverAsyncClient( NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, false, options, connectionProcessor, tracerProvider, messageSerializer); final UUID lockToken1 = UUID.randomUUID(); final UUID lockToken2 = UUID.randomUUID(); final Instant expiration = Instant.now().plus(Duration.ofMinutes(1)); final MessageWithLockToken message = mock(MessageWithLockToken.class); final MessageWithLockToken message2 = mock(MessageWithLockToken.class); when(message.getLockToken()).thenReturn(lockToken1); when(message2.getLockToken()).thenReturn(lockToken2); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(receivedMessage.getLockedUntil()).thenReturn(expiration); when(receivedMessage2.getLockToken()).thenReturn(lockToken2); when(receivedMessage2.getLockedUntil()).thenReturn(expiration); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)) .thenReturn(Mono.just(managementNode)); when(managementNode.updateDisposition(eq(lockToken1), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull())) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); when(managementNode.updateDisposition(eq(lockToken2), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull())) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); StepVerifier.create(consumer2.receive().take(2)) .then(() -> { messageSink.next(message); messageSink.next(message2); }) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); verify(managementNode).updateDisposition(eq(lockToken1), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull()); verify(managementNode).updateDisposition(eq(lockToken2), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull()); } /** * Verifies that if there is no lock token, the message is not completed. */ @Test void receivesAndAutoCompleteWithoutLockToken() { final ReceiveMessageOptions options = new ReceiveMessageOptions().setPrefetchCount(PREFETCH) .setAutoComplete(true); final ServiceBusReceiverAsyncClient consumer2 = new ServiceBusReceiverAsyncClient( NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, false, options, connectionProcessor, tracerProvider, messageSerializer); final MessageWithLockToken message = mock(MessageWithLockToken.class); final MessageWithLockToken message2 = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)) .thenReturn(Mono.just(managementNode)); when(managementNode.updateDisposition(any(), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull())) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); try { StepVerifier.create(consumer2.receive().take(2)) .then(() -> { messageSink.next(message); messageSink.next(message2); }) .expectNext(receivedMessage, receivedMessage2) .expectComplete() .verify(); } finally { consumer2.close(); } verifyZeroInteractions(managementNode); } /** * Verifies that we error if we try to complete a message without a lock token. */ @Test void completeNullLockToken() { when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)).thenReturn(Mono.just(managementNode)); when(managementNode.updateDisposition(any(), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull())) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); when(receivedMessage.getLockToken()).thenReturn(null); StepVerifier.create(consumer.complete(receivedMessage)) .expectError(IllegalArgumentException.class) .verify(); verify(managementNode, times(0)) .updateDisposition(any(), eq(DispositionStatus.COMPLETED), isNull(), isNull(), isNull()); } /** * Verifies that we error if we try to complete a null message. */ @Test void completeNullMessage() { StepVerifier.create(consumer.complete(null)).expectError(NullPointerException.class).verify(); } /** * Verifies that we error if we complete in RECEIVE_AND_DELETE mode. */ @Test void completeInReceiveAndDeleteMode() { final ReceiveMessageOptions options = new ReceiveMessageOptions() .setAutoComplete(false) .setReceiveMode(ReceiveMode.RECEIVE_AND_DELETE); ServiceBusReceiverAsyncClient client = new ServiceBusReceiverAsyncClient(NAMESPACE, ENTITY_PATH, MessagingEntityType.QUEUE, false, options, connectionProcessor, tracerProvider, messageSerializer); final UUID lockToken1 = UUID.randomUUID(); when(receivedMessage.getLockToken()).thenReturn(lockToken1); try { StepVerifier.create(client.complete(receivedMessage)) .expectError(UnsupportedOperationException.class) .verify(); } finally { client.close(); } } /** * Verifies that this peek batch of messages. */ @Test void peekBatchMessages() { final int numberOfEvents = 2; when(managementNode.peekBatch(numberOfEvents)) .thenReturn(Flux.fromArray(new ServiceBusReceivedMessage[]{receivedMessage, receivedMessage2})); StepVerifier.create(consumer.peekBatch(numberOfEvents)) .expectNextCount(numberOfEvents) .verifyComplete(); } /** * Verifies that this peek batch of messages from a sequence Number. */ @Test /** * Verifies that the user can complete settlement methods on received message. */ @ParameterizedTest @EnumSource(DispositionStatus.class) void settleMessage(DispositionStatus dispositionStatus) { final UUID lockToken1 = UUID.randomUUID(); final UUID lockToken2 = UUID.randomUUID(); final Instant expiration = Instant.now().plus(Duration.ofMinutes(5)); final MessageWithLockToken message = mock(MessageWithLockToken.class); final MessageWithLockToken message2 = mock(MessageWithLockToken.class); when(messageSerializer.deserialize(message, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage); when(messageSerializer.deserialize(message2, ServiceBusReceivedMessage.class)).thenReturn(receivedMessage2); when(receivedMessage.getLockToken()).thenReturn(lockToken1); when(receivedMessage.getLockedUntil()).thenReturn(expiration); when(receivedMessage2.getLockToken()).thenReturn(lockToken2); when(receivedMessage2.getLockedUntil()).thenReturn(expiration); when(connection.getManagementNode(ENTITY_PATH, ENTITY_TYPE)) .thenReturn(Mono.just(managementNode)); when(managementNode.updateDisposition(lockToken1, dispositionStatus, null, null, null)) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); when(managementNode.updateDisposition(lockToken2, dispositionStatus, null, null, null)) .thenReturn(Mono.delay(Duration.ofMillis(250)).then()); StepVerifier.create(consumer.receive().take(2)) .then(() -> { messageSink.next(message); messageSink.next(message2); }) .expectNext(receivedMessage, receivedMessage2) .verifyComplete(); final Mono<Void> operation; switch (dispositionStatus) { case DEFERRED: operation = consumer.defer(receivedMessage); break; case ABANDONED: operation = consumer.abandon(receivedMessage); break; case COMPLETED: operation = consumer.complete(receivedMessage); break; case SUSPENDED: operation = consumer.deadLetter(receivedMessage); break; default: throw new IllegalArgumentException("Unrecognized operation: " + dispositionStatus); } StepVerifier.create(operation) .verifyComplete(); verify(managementNode).updateDisposition(lockToken1, dispositionStatus, null, null, null); verify(managementNode, times(0)).updateDisposition(lockToken2, dispositionStatus, null, null, null); } private List<Message> getMessages(int numberOfEvents) { final Map<String, String> map = Collections.singletonMap("SAMPLE_HEADER", "foo"); return IntStream.range(0, numberOfEvents) .mapToObj(index -> getMessage(PAYLOAD_BYTES, messageTrackingUUID, map)) .collect(Collectors.toList()); } }
replace with: Mono.when()
void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(sender.send(message) .then(sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); }
StepVerifier.create(sender.send(message)
void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); Assertions.assertEquals(messageId, receivedMessage.getProperties().get(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); Assertions.assertEquals(messageId, receivedMessage.getProperties().get(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequencenumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, receivedMessage.getBodyAsString()); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); Assertions.assertEquals(messageId, receivedMessage.getProperties().get(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(sender.send(message) .then(sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } }
This should be removed form API
public String getContentType() { return contentType; }
}
public String getContentType() { return contentType; }
class ServiceBusMessage { private final Map<String, Object> properties; private final byte[] body; private Context context; private String contentType; private String correlationId; private String label; private String messageId; private String partitionKey; private String replyTo; private String replyToSessionId; private Instant scheduledEnqueueTime; private String sessionId; private Duration timeToLive; private String to; private String viaPartitionKey; /** * Creates a {@link ServiceBusMessage} containing the {@code body}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. */ public ServiceBusMessage(byte[] body) { this.body = Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.properties = new HashMap<>(); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. */ public ServiceBusMessage(ByteBuffer body) { this(body.array()); } /** * Creates a {@link ServiceBusMessage} by encoding the {@code body} using UTF-8 charset. * * @param body The string that will be UTF-8 encoded to create a {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. */ public ServiceBusMessage(String body) { this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(UTF_8)); } /** * Creates a message from a string. For backward compatibility reasons, the string is converted to a byte array and * message body type is set to binary. * * @param body body of the message * @param contentType body type of the message */ public ServiceBusMessage(String body, String contentType) { this(body.getBytes(UTF_8), contentType); } /** * Creates a message from a byte array. Message body type is set to binary. * * @param body body of the message * @param contentType content type of the message */ public ServiceBusMessage(byte[] body, String contentType) { this(body); this.contentType = contentType; } /** * Creates a message from a string. For backward compatibility reasons, the string is converted to a byte array. * * @param messageId id of the {@link ServiceBusMessage}. * @param body body of the {@link ServiceBusMessage}. * @param contentType content type of the {@link ServiceBusMessage}. */ public ServiceBusMessage(String messageId, String body, String contentType) { this(messageId, body.getBytes(UTF_8), contentType); } /** * Creates a {@link ServiceBusMessage} from a byte array. * * @param messageId id of the {@link ServiceBusMessage}. * @param body body of the {@link ServiceBusMessage}. * @param contentType content type of the {@link ServiceBusMessage}. */ public ServiceBusMessage(String messageId, byte[] body, String contentType) { this(body, contentType); this.messageId = messageId; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code properties()} is * to associate serialization hints for the {@link * binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getProperties() { return properties; } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public byte[] getBody() { return Arrays.copyOf(body, body.length); } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { this.contentType = contentType; return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { this.correlationId = correlationId; return this; } /** * Gets the label for the message. * * @return The label for the message. */ public String getLabel() { return label; } /** * Sets the label for the message. * * @param label The label to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setLabel(String label) { this.label = label; return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return messageId; } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { this.messageId = messageId; return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * * @see <a href="https: * entities</a> */ public String getPartitionKey() { return partitionKey; } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setReplyTo(String replyTo) { this.replyTo = replyTo; return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return to; } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { this.to = to; return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * * @see <a href="https: */ public Duration getTimeToLive() { return timeToLive; } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { this.timeToLive = timeToLive; return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given instant; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the instant at which the message will be enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public Instant getScheduledEnqueueTime() { return scheduledEnqueueTime; } /** * Sets the scheduled enqueue time of this message. * * @param scheduledEnqueueTime the instant at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setScheduledEnqueueTime(Instant scheduledEnqueueTime) { this.scheduledEnqueueTime = scheduledEnqueueTime; return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return replyToSessionId; } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { this.replyToSessionId = replyToSessionId; return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the * transfer queue partition: This is functionally equivalent to {@link * messages are kept together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: */ public String getViaPartitionKey() { return viaPartitionKey; } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { this.viaPartitionKey = viaPartitionKey; return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return sessionId; } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } }
class ServiceBusMessage { private final Map<String, Object> properties; private final byte[] body; private Context context; private String contentType; private String correlationId; private String label; private String messageId; private String partitionKey; private String replyTo; private String replyToSessionId; private Instant scheduledEnqueueTime; private String sessionId; private Duration timeToLive; private String to; private String viaPartitionKey; /** * Creates a {@link ServiceBusMessage} containing the {@code body}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. */ public ServiceBusMessage(byte[] body) { this.body = Objects.requireNonNull(body, "'body' cannot be null."); this.context = Context.NONE; this.properties = new HashMap<>(); } /** * Creates a {@link ServiceBusMessage} containing the {@code body}. * * @param body The data to set for this {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. */ public ServiceBusMessage(ByteBuffer body) { this(body.array()); } /** * Creates a {@link ServiceBusMessage} by encoding the {@code body} using UTF-8 charset. * * @param body The string that will be UTF-8 encoded to create a {@link ServiceBusMessage}. * * @throws NullPointerException if {@code body} is {@code null}. */ public ServiceBusMessage(String body) { this(Objects.requireNonNull(body, "'body' cannot be null.").getBytes(UTF_8)); } /** * Creates a message from a string. For backward compatibility reasons, the string is converted to a byte array and * message body type is set to binary. * * @param body body of the message * @param contentType body type of the message */ public ServiceBusMessage(String body, String contentType) { this(body.getBytes(UTF_8), contentType); } /** * Creates a message from a byte array. Message body type is set to binary. * * @param body body of the message * @param contentType content type of the message */ public ServiceBusMessage(byte[] body, String contentType) { this(body); this.contentType = contentType; } /** * Creates a message from a string. For backward compatibility reasons, the string is converted to a byte array. * * @param messageId id of the {@link ServiceBusMessage}. * @param body body of the {@link ServiceBusMessage}. * @param contentType content type of the {@link ServiceBusMessage}. */ public ServiceBusMessage(String messageId, String body, String contentType) { this(messageId, body.getBytes(UTF_8), contentType); } /** * Creates a {@link ServiceBusMessage} from a byte array. * * @param messageId id of the {@link ServiceBusMessage}. * @param body body of the {@link ServiceBusMessage}. * @param contentType content type of the {@link ServiceBusMessage}. */ public ServiceBusMessage(String messageId, byte[] body, String contentType) { this(body, contentType); this.messageId = messageId; } /** * Gets the set of free-form {@link ServiceBusMessage} properties which may be used for passing metadata associated * with the {@link ServiceBusMessage} during Service Bus operations. A common use-case for {@code properties()} is * to associate serialization hints for the {@link * binary data. * * @return Application properties associated with this {@link ServiceBusMessage}. */ public Map<String, Object> getProperties() { return properties; } /** * Gets the actual payload/data wrapped by the {@link ServiceBusMessage}. * * <p> * If the means for deserializing the raw data is not apparent to consumers, a common technique is to make use of * {@link * wish to deserialize the binary data. * </p> * * @return A byte array representing the data. */ public byte[] getBody() { return Arrays.copyOf(body, body.length); } /** * Gets the content type of the message. * * @return the contentType of the {@link ServiceBusMessage}. */ /** * Sets the content type of the {@link ServiceBusMessage}. * * @param contentType of the message. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setContentType(String contentType) { this.contentType = contentType; return this; } /** * Gets a correlation identifier. * <p> * Allows an application to specify a context for the message for the purposes of correlation, for example * reflecting the MessageId of a message that is being replied to. * </p> * * @return correlation id of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getCorrelationId() { return correlationId; } /** * Sets a correlation identifier. * * @param correlationId correlation id of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setCorrelationId(String correlationId) { this.correlationId = correlationId; return this; } /** * Gets the label for the message. * * @return The label for the message. */ public String getLabel() { return label; } /** * Sets the label for the message. * * @param label The label to set. * * @return The updated {@link ServiceBusMessage} object. */ public ServiceBusMessage setLabel(String label) { this.label = label; return this; } /** * @return Id of the {@link ServiceBusMessage}. */ public String getMessageId() { return messageId; } /** * Sets the message id. * * @param messageId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setMessageId(String messageId) { this.messageId = messageId; return this; } /** * Gets the partition key for sending a message to a partitioned entity. * <p> * For <a href="https: * entities</a>, setting this value enables assigning related messages to the same internal partition, so that * submission sequence order is correctly recorded. The partition is chosen by a hash function over this value and * cannot be chosen directly. For session-aware entities, the {@link * this value. * * @return The partition key of this message * * @see <a href="https: * entities</a> */ public String getPartitionKey() { return partitionKey; } /** * Sets a partition key for sending a message to a partitioned entity * * @param partitionKey partition key of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setPartitionKey(String partitionKey) { this.partitionKey = partitionKey; return this; } /** * Gets the address of an entity to send replies to. * <p> * This optional and application-defined value is a standard way to express a reply path to the receiver of the * message. When a sender expects a reply, it sets the value to the absolute or relative path of the queue or topic * it expects the reply to be sent to. * * @return ReplyTo property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyTo() { return replyTo; } /** * Sets the address of an entity to send replies to. * * @param replyTo ReplyTo property value of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setReplyTo(String replyTo) { this.replyTo = replyTo; return this; } /** * Gets the "to" address. * * @return "To" property value of this message */ public String getTo() { return to; } /** * Sets the "to" address. * <p> * This property is reserved for future use in routing scenarios and presently ignored by the broker itself. * Applications can use this value in rule-driven * <a href="https: * chaining</a> scenarios to indicate the intended logical destination of the message. * * @param to To property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setTo(String to) { this.to = to; return this; } /** * Gets the duration before this message expires. * <p> * This value is the relative duration after which the message expires, starting from the instant the message has * been accepted and stored by the broker, as captured in {@link * explicitly, the assumed value is the DefaultTimeToLive set for the respective queue or topic. A message-level * TimeToLive value cannot be longer than the entity's DefaultTimeToLive setting and it is silently adjusted if it * does. * * @return Time to live duration of this message * * @see <a href="https: */ public Duration getTimeToLive() { return timeToLive; } /** * Sets the duration of time before this message expires. * * @param timeToLive Time to Live duration of this message * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setTimeToLive(Duration timeToLive) { this.timeToLive = timeToLive; return this; } /** * Gets the scheduled enqueue time of this message. * <p> * This value is used for delayed message availability. The message is safely added to the queue, but is not * considered active and therefore not retrievable until the scheduled enqueue time. Mind that the message may not * be activated (enqueued) at the exact given instant; the actual activation time depends on the queue's workload * and its state. * </p> * * @return the instant at which the message will be enqueued in Azure Service Bus * * @see <a href="https: * Timestamps</a> */ public Instant getScheduledEnqueueTime() { return scheduledEnqueueTime; } /** * Sets the scheduled enqueue time of this message. * * @param scheduledEnqueueTime the instant at which this message should be enqueued in Azure Service Bus. * * @return The updated {@link ServiceBusMessage}. * * @see */ public ServiceBusMessage setScheduledEnqueueTime(Instant scheduledEnqueueTime) { this.scheduledEnqueueTime = scheduledEnqueueTime; return this; } /** * Gets or sets a session identifier augmenting the {@link * <p> * This value augments the ReplyTo information and specifies which SessionId should be set for the reply when sent * to the reply entity. * * @return ReplyToSessionId property value of this message * * @see <a href="https: * Routing and Correlation</a> */ public String getReplyToSessionId() { return replyToSessionId; } /** * Gets or sets a session identifier augmenting the {@link * * @param replyToSessionId ReplyToSessionId property value of this message * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setReplyToSessionId(String replyToSessionId) { this.replyToSessionId = replyToSessionId; return this; } /** * Gets the partition key for sending a message to a entity via another partitioned transfer entity. * * If a message is sent via a transfer queue in the scope of a transaction, this value selects the * transfer queue partition: This is functionally equivalent to {@link * messages are kept together and in order as they are transferred. * * @return partition key on the via queue. * @see <a href="https: */ public String getViaPartitionKey() { return viaPartitionKey; } /** * Sets a via-partition key for sending a message to a destination entity via another partitioned entity * * @param viaPartitionKey via-partition key of this message * @return The updated {@link ServiceBusMessage}. * @see */ public ServiceBusMessage setViaPartitionKey(String viaPartitionKey) { this.viaPartitionKey = viaPartitionKey; return this; } /** * Gets the session id of the message. * * @return Session Id of the {@link ServiceBusMessage}. */ public String getSessionId() { return sessionId; } /** * Sets the session id. * * @param sessionId to be set. * * @return The updated {@link ServiceBusMessage}. */ public ServiceBusMessage setSessionId(String sessionId) { this.sessionId = sessionId; return this; } /** * A specified key-value pair of type {@link Context} to set additional information on the {@link * ServiceBusMessage}. * * @return the {@link Context} object set on the {@link ServiceBusMessage}. */ Context getContext() { return context; } /** * Adds a new key value pair to the existing context on Message. * * @param key The key for this context object * @param value The value for this context object. * * @return The updated {@link ServiceBusMessage}. * * @throws NullPointerException if {@code key} or {@code value} is null. */ public ServiceBusMessage addContext(String key, Object value) { Objects.requireNonNull(key, "The 'key' parameter cannot be null."); Objects.requireNonNull(value, "The 'value' parameter cannot be null."); this.context = context.addData(key, value); return this; } }
detectLanguageWithCountryHint() uses `String input`
public void detectLanguage() { String document = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(document).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); }
public void detectLanguage() { String document = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(document).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); }
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); return textAnalyticsAsyncClient; } /** * Code snippet for updating the existing API key. */ public void rotateApiKey() { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); credential.updateCredential("{new_api_key}"); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageWithCountryHint() { String input = "This text is in English"; String countryHint = "US"; textAnalyticsAsyncClient.detectLanguage(input, countryHint).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringList() { final List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español."); textAnalyticsAsyncClient.detectLanguageBatch(documents).byPage().subscribe(batchResult -> { final TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithCountryHint() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US").byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithOptions() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US", null).byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectBatchLanguagesMaxOverload() { List<DetectLanguageInput> detectLanguageInputs1 = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "US"), new DetectLanguageInput("2", "Este es un documento escrito en Español.", "ES") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.detectLanguageBatch(detectLanguageInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : response.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntities() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document) .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesWithLanguage() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document, "en") .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringList() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft." ); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents).byPage().subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity sub-category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntities() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document).subscribe(piiEntity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesWithLanguage() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document, "en") .subscribe(entity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringList() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111."); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents).byPage().subscribe(recognizeEntitiesResults -> { TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); recognizeEntitiesResults.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchPiiEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "My SSN is 555-55-5555."), new TextDocumentInput("1", "Visa card 0111 1111 1111 1111.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntities() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document).subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesWithLanguage() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document, "en") .subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringList() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchLinkedEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "Old Faithful is a geyser at Yellowstone Park."), new TextDocumentInput("1", "Mount Shasta has lenticular clouds.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %.2f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrases() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde").subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesWithLanguage() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde", "fr") .subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringList() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents).byPage().subscribe(extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en").byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithOptions() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en", null).byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void extractBatchKeyPhrasesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.extractKeyPhrasesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (ExtractKeyPhraseResult extractKeyPhraseResult : response.getElements()) { System.out.println("Extracted phrases:"); for (String keyPhrase : extractKeyPhraseResult.getKeyPhrases()) { System.out.printf("%s.%n", keyPhrase); } } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentiment() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document).subscribe(documentSentiment -> { System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf( "Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentWithLanguage() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document, "en") .subscribe(documentSentiment -> { System.out.printf("Recognized sentiment label: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringList() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi."); textAnalyticsAsyncClient.analyzeSentimentBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithLanguageCode() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en").byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithOptions() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en", null).byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void analyzeBatchSentimentMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "The hotel was dark and unclean."), new TextDocumentInput("1", "The restaurant had amazing gnocchi.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.analyzeSentimentBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } public void textAnalyticsPagedFluxSample() { TextAnalyticsPagedFlux<CategorizedEntity> pagedFlux = textAnalyticsAsyncClient.recognizeEntities(""); pagedFlux .log() .subscribe( item -> System.out.println("Processing item" + item), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); pagedFlux .byPage() .log() .subscribe( page -> System.out.printf("Processing page containing model version: %s, items:", page.getModelVersion(), page.getElements()), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); } }
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); return textAnalyticsAsyncClient; } /** * Code snippet for updating the existing API key. */ public void rotateApiKey() { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); credential.updateCredential("{new_api_key}"); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageWithCountryHint() { String document = "This text is in English"; String countryHint = "US"; textAnalyticsAsyncClient.detectLanguage(document, countryHint).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringList() { final List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español."); textAnalyticsAsyncClient.detectLanguageBatch(documents).byPage().subscribe(batchResult -> { final TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithCountryHint() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US").byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithOptions() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US", null).byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectBatchLanguagesMaxOverload() { List<DetectLanguageInput> detectLanguageInputs1 = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "US"), new DetectLanguageInput("2", "Este es un documento escrito en Español.", "ES") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.detectLanguageBatch(detectLanguageInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : response.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntities() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document) .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesWithLanguage() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document, "en") .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringList() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft." ); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents).byPage().subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity sub-category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntities() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document).subscribe(piiEntity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesWithLanguage() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document, "en") .subscribe(entity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringList() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111."); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents).byPage().subscribe(recognizeEntitiesResults -> { TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); recognizeEntitiesResults.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchPiiEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "My SSN is 555-55-5555."), new TextDocumentInput("1", "Visa card 0111 1111 1111 1111.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntities() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document).subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesWithLanguage() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document, "en") .subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringList() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchLinkedEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "Old Faithful is a geyser at Yellowstone Park."), new TextDocumentInput("1", "Mount Shasta has lenticular clouds.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %.2f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrases() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde").subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesWithLanguage() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde", "fr") .subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringList() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents).byPage().subscribe(extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en").byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithOptions() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en", null).byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void extractBatchKeyPhrasesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.extractKeyPhrasesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (ExtractKeyPhraseResult extractKeyPhraseResult : response.getElements()) { System.out.println("Extracted phrases:"); for (String keyPhrase : extractKeyPhraseResult.getKeyPhrases()) { System.out.printf("%s.%n", keyPhrase); } } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentiment() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document).subscribe(documentSentiment -> { System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf( "Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentWithLanguage() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document, "en") .subscribe(documentSentiment -> { System.out.printf("Recognized sentiment label: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringList() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi."); textAnalyticsAsyncClient.analyzeSentimentBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithLanguageCode() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en").byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithOptions() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en", null).byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void analyzeBatchSentimentMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "The hotel was dark and unclean."), new TextDocumentInput("1", "The restaurant had amazing gnocchi.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.analyzeSentimentBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } public void textAnalyticsPagedFluxSample() { TextAnalyticsPagedFlux<CategorizedEntity> pagedFlux = textAnalyticsAsyncClient.recognizeEntities(""); pagedFlux .log() .subscribe( item -> System.out.println("Processing item" + item), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); pagedFlux .byPage() .log() .subscribe( page -> System.out.printf("Processing page containing model version: %s, items:", page.getModelVersion(), page.getElements()), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); } }
updated
public void detectLanguage() { String document = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(document).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); }
public void detectLanguage() { String document = "Bonjour tout le monde"; textAnalyticsAsyncClient.detectLanguage(document).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); }
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); return textAnalyticsAsyncClient; } /** * Code snippet for updating the existing API key. */ public void rotateApiKey() { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); credential.updateCredential("{new_api_key}"); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageWithCountryHint() { String input = "This text is in English"; String countryHint = "US"; textAnalyticsAsyncClient.detectLanguage(input, countryHint).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringList() { final List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español."); textAnalyticsAsyncClient.detectLanguageBatch(documents).byPage().subscribe(batchResult -> { final TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithCountryHint() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US").byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithOptions() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US", null).byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectBatchLanguagesMaxOverload() { List<DetectLanguageInput> detectLanguageInputs1 = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "US"), new DetectLanguageInput("2", "Este es un documento escrito en Español.", "ES") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.detectLanguageBatch(detectLanguageInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : response.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntities() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document) .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesWithLanguage() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document, "en") .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringList() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft." ); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents).byPage().subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity sub-category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntities() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document).subscribe(piiEntity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesWithLanguage() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document, "en") .subscribe(entity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringList() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111."); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents).byPage().subscribe(recognizeEntitiesResults -> { TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); recognizeEntitiesResults.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchPiiEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "My SSN is 555-55-5555."), new TextDocumentInput("1", "Visa card 0111 1111 1111 1111.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntities() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document).subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesWithLanguage() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document, "en") .subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringList() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchLinkedEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "Old Faithful is a geyser at Yellowstone Park."), new TextDocumentInput("1", "Mount Shasta has lenticular clouds.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %.2f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrases() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde").subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesWithLanguage() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde", "fr") .subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringList() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents).byPage().subscribe(extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en").byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithOptions() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en", null).byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void extractBatchKeyPhrasesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.extractKeyPhrasesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (ExtractKeyPhraseResult extractKeyPhraseResult : response.getElements()) { System.out.println("Extracted phrases:"); for (String keyPhrase : extractKeyPhraseResult.getKeyPhrases()) { System.out.printf("%s.%n", keyPhrase); } } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentiment() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document).subscribe(documentSentiment -> { System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf( "Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentWithLanguage() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document, "en") .subscribe(documentSentiment -> { System.out.printf("Recognized sentiment label: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringList() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi."); textAnalyticsAsyncClient.analyzeSentimentBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithLanguageCode() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en").byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithOptions() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en", null).byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void analyzeBatchSentimentMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "The hotel was dark and unclean."), new TextDocumentInput("1", "The restaurant had amazing gnocchi.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.analyzeSentimentBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } public void textAnalyticsPagedFluxSample() { TextAnalyticsPagedFlux<CategorizedEntity> pagedFlux = textAnalyticsAsyncClient.recognizeEntities(""); pagedFlux .log() .subscribe( item -> System.out.println("Processing item" + item), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); pagedFlux .byPage() .log() .subscribe( page -> System.out.printf("Processing page containing model version: %s, items:", page.getModelVersion(), page.getElements()), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); } }
class TextAnalyticsAsyncClientJavaDocCodeSnippets { TextAnalyticsAsyncClient textAnalyticsAsyncClient = createTextAnalyticsAsyncClient(); /** * Code snippet for creating a {@link TextAnalyticsAsyncClient} * * @return The TextAnalyticsAsyncClient object */ public TextAnalyticsAsyncClient createTextAnalyticsAsyncClient() { TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(new TextAnalyticsApiKeyCredential("{api_key}")) .endpoint("{endpoint}") .buildAsyncClient(); return textAnalyticsAsyncClient; } /** * Code snippet for updating the existing API key. */ public void rotateApiKey() { TextAnalyticsApiKeyCredential credential = new TextAnalyticsApiKeyCredential("{api_key}"); TextAnalyticsAsyncClient textAnalyticsAsyncClient = new TextAnalyticsClientBuilder() .apiKey(credential) .endpoint("{endpoint}") .buildAsyncClient(); credential.updateCredential("{new_api_key}"); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageWithCountryHint() { String document = "This text is in English"; String countryHint = "US"; textAnalyticsAsyncClient.detectLanguage(document, countryHint).subscribe(detectedLanguage -> System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringList() { final List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español."); textAnalyticsAsyncClient.detectLanguageBatch(documents).byPage().subscribe(batchResult -> { final TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithCountryHint() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US").byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectLanguageStringListWithOptions() { List<String> documents = Arrays.asList( "This is written in English", "Este es un documento escrito en Español." ); textAnalyticsAsyncClient.detectLanguageBatch(documents, "US", null).byPage().subscribe( batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : batchResult.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void detectBatchLanguagesMaxOverload() { List<DetectLanguageInput> detectLanguageInputs1 = Arrays.asList( new DetectLanguageInput("1", "This is written in English.", "US"), new DetectLanguageInput("2", "Este es un documento escrito en Español.", "ES") ); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.detectLanguageBatch(detectLanguageInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (DetectLanguageResult detectLanguageResult : response.getElements()) { DetectedLanguage detectedLanguage = detectLanguageResult.getPrimaryLanguage(); System.out.printf("Detected language name: %s, ISO 6391 Name: %s, score: %f.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntities() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document) .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesWithLanguage() { String document = "Satya Nadella is the CEO of Microsoft"; textAnalyticsAsyncClient.recognizeEntities(document, "en") .subscribe(entity -> System.out.printf("Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringList() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft." ); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents).byPage().subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized entity: %s, entity category: %s, entity sub-category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getSubCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "I had a wonderful trip to Seattle last week.", "I work at Microsoft."); textAnalyticsAsyncClient.recognizeEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(entity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntities() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document).subscribe(piiEntity -> System.out.printf( "Recognized categorized entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesWithLanguage() { String document = "My SSN is 555-55-5555"; textAnalyticsAsyncClient.recognizePiiEntities(document, "en") .subscribe(entity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", entity.getText(), entity.getCategory(), entity.getConfidenceScore())); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringList() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111."); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents).byPage().subscribe(recognizeEntitiesResults -> { TextDocumentBatchStatistics batchStatistics = recognizeEntitiesResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); recognizeEntitiesResults.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizePiiEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "My SSN is 555-55-5555.", "Visa card 0111 1111 1111 1111." ); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchPiiEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "My SSN is 555-55-5555."), new TextDocumentInput("1", "Visa card 0111 1111 1111 1111.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizePiiEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeEntitiesResult -> recognizeEntitiesResult.getEntities().forEach(piiEntity -> System.out.printf( "Recognized Personally Identifiable Information entity: %s, category: %s, score: %f.%n", piiEntity.getText(), piiEntity.getCategory(), piiEntity.getConfidenceScore()))); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntities() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document).subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesWithLanguage() { String document = "Old Faithful is a geyser at Yellowstone Park."; textAnalyticsAsyncClient.recognizeLinkedEntities(document, "en") .subscribe(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringList() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en").byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void recognizeLinkedEntitiesStringListWithOptions() { List<String> documents = Arrays.asList( "Old Faithful is a geyser at Yellowstone Park.", "Mount Shasta has lenticular clouds." ); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(documents, "en", null).byPage() .subscribe(batchResult -> { TextDocumentBatchStatistics batchStatistics = batchResult.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); batchResult.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void recognizeBatchLinkedEntitiesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "Old Faithful is a geyser at Yellowstone Park."), new TextDocumentInput("1", "Mount Shasta has lenticular clouds.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.recognizeLinkedEntitiesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(recognizeLinkedEntitiesResult -> recognizeLinkedEntitiesResult.getEntities().forEach(linkedEntity -> { System.out.println("Linked Entities:"); System.out.printf("Name: %s, entity ID in data source: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getDataSourceEntityId(), linkedEntity.getUrl(), linkedEntity.getDataSource()); linkedEntity.getLinkedEntityMatches().forEach(entityMatch -> System.out.printf( "Matched entity: %s, score: %.2f.%n", entityMatch.getText(), entityMatch.getConfidenceScore())); })); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrases() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde").subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesWithLanguage() { System.out.println("Extracted phrases:"); textAnalyticsAsyncClient.extractKeyPhrases("Bonjour tout le monde", "fr") .subscribe(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringList() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents).byPage().subscribe(extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithLanguageCode() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en").byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void extractKeyPhrasesStringListWithOptions() { List<String> documents = Arrays.asList( "Hello world. This is some input text that I love.", "Bonjour tout le monde"); textAnalyticsAsyncClient.extractKeyPhrasesBatch(documents, "en", null).byPage().subscribe( extractKeyPhraseResults -> { TextDocumentBatchStatistics batchStatistics = extractKeyPhraseResults.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); extractKeyPhraseResults.getElements().forEach(extractKeyPhraseResult -> { System.out.println("Extracted phrases:"); extractKeyPhraseResult.getKeyPhrases().forEach(keyPhrase -> System.out.printf("%s.%n", keyPhrase)); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void extractBatchKeyPhrasesMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "I had a wonderful trip to Seattle last week."), new TextDocumentInput("1", "I work at Microsoft.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.extractKeyPhrasesBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); for (ExtractKeyPhraseResult extractKeyPhraseResult : response.getElements()) { System.out.println("Extracted phrases:"); for (String keyPhrase : extractKeyPhraseResult.getKeyPhrases()) { System.out.printf("%s.%n", keyPhrase); } } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentiment() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document).subscribe(documentSentiment -> { System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf( "Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentWithLanguage() { String document = "The hotel was dark and unclean."; textAnalyticsAsyncClient.analyzeSentiment(document, "en") .subscribe(documentSentiment -> { System.out.printf("Recognized sentiment label: %s.%n", documentSentiment.getSentiment()); for (SentenceSentiment sentenceSentiment : documentSentiment.getSentences()) { System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative()); } }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringList() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi."); textAnalyticsAsyncClient.analyzeSentimentBatch(documents).byPage().subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, neutral score: %.2f, " + "negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithLanguageCode() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en").byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient */ public void analyzeSentimentStringListWithOptions() { List<String> documents = Arrays.asList( "The hotel was dark and unclean.", "The restaurant had amazing gnocchi." ); textAnalyticsAsyncClient.analyzeSentimentBatch(documents, "en", null).byPage().subscribe( response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } /** * Code snippet for {@link TextAnalyticsAsyncClient * TextAnalyticsRequestOptions)} */ public void analyzeBatchSentimentMaxOverload() { List<TextDocumentInput> textDocumentInputs1 = Arrays.asList( new TextDocumentInput("0", "The hotel was dark and unclean."), new TextDocumentInput("1", "The restaurant had amazing gnocchi.")); TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setIncludeStatistics(true); textAnalyticsAsyncClient.analyzeSentimentBatch(textDocumentInputs1, requestOptions).byPage() .subscribe(response -> { TextDocumentBatchStatistics batchStatistics = response.getStatistics(); System.out.printf("Batch statistics, transaction count: %s, valid document count: %s.%n", batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); response.getElements().forEach(analyzeSentimentResult -> { System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); DocumentSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); System.out.printf("Recognized document sentiment: %s.%n", documentSentiment.getSentiment()); documentSentiment.getSentences().forEach(sentenceSentiment -> System.out.printf("Recognized sentence sentiment: %s, positive score: %.2f, " + "neutral score: %.2f, negative score: %.2f.%n", sentenceSentiment.getSentiment(), sentenceSentiment.getConfidenceScores().getPositive(), sentenceSentiment.getConfidenceScores().getNeutral(), sentenceSentiment.getConfidenceScores().getNegative())); }); }); } public void textAnalyticsPagedFluxSample() { TextAnalyticsPagedFlux<CategorizedEntity> pagedFlux = textAnalyticsAsyncClient.recognizeEntities(""); pagedFlux .log() .subscribe( item -> System.out.println("Processing item" + item), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); pagedFlux .byPage() .log() .subscribe( page -> System.out.printf("Processing page containing model version: %s, items:", page.getModelVersion(), page.getElements()), error -> System.err.println("Error occurred " + error), () -> System.out.println("Completed processing.")); } }
PagedIterable/PagedFlux is already doing what need to be done on paged response. This class is only a wrapper to provide interface compatible with v1.
protected void loadNextPage() { this.items.addAll(pagedResponseIterator.next().getValue()); }
this.items.addAll(pagedResponseIterator.next().getValue());
protected void loadNextPage() { this.items.addAll(pagedResponseIterator.next().getValue()); }
class PagedList<E> implements List<E> { /** The items retrieved. */ private final List<E> items; /** The paged response iterator for not retrieved items. */ private Iterator<PagedResponse<E>> pagedResponseIterator; /** * Creates an instance of PagedList. */ public PagedList() { items = new ArrayList<>(); pagedResponseIterator = Collections.emptyIterator(); } /** * Creates an instance of PagedList from a {@link PagedIterable}. * * @param pagedIterable the {@link PagedIterable} object. */ public PagedList(PagedIterable<E> pagedIterable) { items = new ArrayList<>(); Objects.requireNonNull(pagedIterable, "'pagedIterable' cannot be null."); this.pagedResponseIterator = pagedIterable.iterableByPage().iterator(); } /** * If there are more pages available. * * @return true if there are more pages to load. False otherwise. */ protected boolean hasNextPage() { return pagedResponseIterator.hasNext(); } /** * Loads a page from next page link. * The exceptions are wrapped into Java Runtime exceptions. */ /** * Keep loading the next page from the next page link until all items are loaded. */ public void loadAll() { while (hasNextPage()) { loadNextPage(); } } @Override public int size() { loadAll(); return items.size(); } @Override public boolean isEmpty() { return items.isEmpty() && !hasNextPage(); } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Iterator<E> iterator() { return new ListItr(0); } @Override public Object[] toArray() { loadAll(); return items.toArray(); } @Override public <T> T[] toArray(T[] a) { loadAll(); return items.toArray(a); } @Override public boolean add(E e) { loadAll(); return items.add(e); } @Override public boolean remove(Object o) { int index = indexOf(o); if (index != -1) { items.remove(index); return true; } else { return false; } } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) { if (!contains(e)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends E> c) { return items.addAll(c); } @Override public boolean addAll(int index, Collection<? extends E> c) { return items.addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return items.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return items.retainAll(c); } @Override public void clear() { items.clear(); pagedResponseIterator = Collections.emptyIterator(); } @Override public E get(int index) { tryLoadToIndex(index); return items.get(index); } @Override public E set(int index, E element) { tryLoadToIndex(index); return items.set(index, element); } @Override public void add(int index, E element) { items.add(index, element); } @Override public E remove(int index) { tryLoadToIndex(index); return items.remove(index); } @Override public int indexOf(Object o) { int index = items.indexOf(o); if (index != -1) { return index; } while (hasNextPage()) { int itemsSize = items.size(); List<E> nextPageItems = pagedResponseIterator.next().getValue(); this.items.addAll(nextPageItems); index = nextPageItems.indexOf(o); if (index != -1) { index = itemsSize + index; return index; } } return -1; } @Override public int lastIndexOf(Object o) { loadAll(); return items.lastIndexOf(o); } @Override public ListIterator<E> listIterator() { return new ListItr(0); } @Override public ListIterator<E> listIterator(int index) { tryLoadToIndex(index); return new ListItr(index); } @Override public List<E> subList(int fromIndex, int toIndex) { while ((fromIndex >= items.size() || toIndex >= items.size()) && hasNextPage()) { loadNextPage(); } return items.subList(fromIndex, toIndex); } private void tryLoadToIndex(int index) { while (index >= items.size() && hasNextPage()) { loadNextPage(); } } /** * The implementation of {@link ListIterator} for PagedList. */ private class ListItr implements ListIterator<E> { /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIterator. * * @param index the position in the list to start. */ ListItr(int index) { this.nextIndex = index; } @Override public boolean hasNext() { return this.nextIndex != items.size() || hasNextPage(); } @Override public E next() { if (this.nextIndex >= items.size()) { if (!hasNextPage()) { throw new NoSuchElementException(); } else { loadNextPage(); } return next(); } else { try { E nextItem = items.get(this.nextIndex); this.lastRetIndex = this.nextIndex; this.nextIndex = this.nextIndex + 1; return nextItem; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void remove() { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public boolean hasPrevious() { return this.nextIndex != 0; } @Override public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw new NoSuchElementException(); } else if (i >= items.size()) { throw new ConcurrentModificationException(); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetIndex); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public int nextIndex() { return this.nextIndex; } @Override public int previousIndex() { return this.nextIndex - 1; } @Override public void set(E e) { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.set(this.lastRetIndex, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void add(E e) { try { items.add(this.nextIndex, e); this.nextIndex = this.nextIndex + 1; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } }
class PagedList<E> implements List<E> { /** The items retrieved. */ private final List<E> items; /** The paged response iterator for not retrieved items. */ private Iterator<PagedResponse<E>> pagedResponseIterator; /** * Creates an instance of PagedList. */ public PagedList() { items = new ArrayList<>(); pagedResponseIterator = Collections.emptyIterator(); } /** * Creates an instance of PagedList from a {@link PagedIterable}. * * @param pagedIterable the {@link PagedIterable} object. */ public PagedList(PagedIterable<E> pagedIterable) { items = new ArrayList<>(); Objects.requireNonNull(pagedIterable, "'pagedIterable' cannot be null."); this.pagedResponseIterator = pagedIterable.iterableByPage().iterator(); } /** * If there are more pages available. * * @return true if there are more pages to load. False otherwise. */ protected boolean hasNextPage() { return pagedResponseIterator.hasNext(); } /** * Loads a page from next page link. * The exceptions are wrapped into Java Runtime exceptions. */ /** * Keep loading the next page from the next page link until all items are loaded. */ public void loadAll() { while (hasNextPage()) { loadNextPage(); } } @Override public int size() { loadAll(); return items.size(); } @Override public boolean isEmpty() { return items.isEmpty() && !hasNextPage(); } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Iterator<E> iterator() { return new ListItr(0); } @Override public Object[] toArray() { loadAll(); return items.toArray(); } @Override public <T> T[] toArray(T[] a) { loadAll(); return items.toArray(a); } @Override public boolean add(E e) { loadAll(); return items.add(e); } @Override public boolean remove(Object o) { int index = indexOf(o); if (index != -1) { items.remove(index); return true; } else { return false; } } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) { if (!contains(e)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends E> c) { return items.addAll(c); } @Override public boolean addAll(int index, Collection<? extends E> c) { return items.addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return items.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return items.retainAll(c); } @Override public void clear() { items.clear(); pagedResponseIterator = Collections.emptyIterator(); } @Override public E get(int index) { tryLoadToIndex(index); return items.get(index); } @Override public E set(int index, E element) { tryLoadToIndex(index); return items.set(index, element); } @Override public void add(int index, E element) { items.add(index, element); } @Override public E remove(int index) { tryLoadToIndex(index); return items.remove(index); } @Override public int indexOf(Object o) { int index = items.indexOf(o); if (index != -1) { return index; } while (hasNextPage()) { int itemsSize = items.size(); List<E> nextPageItems = pagedResponseIterator.next().getValue(); this.items.addAll(nextPageItems); index = nextPageItems.indexOf(o); if (index != -1) { index = itemsSize + index; return index; } } return -1; } @Override public int lastIndexOf(Object o) { loadAll(); return items.lastIndexOf(o); } @Override public ListIterator<E> listIterator() { return new ListItr(0); } @Override public ListIterator<E> listIterator(int index) { tryLoadToIndex(index); return new ListItr(index); } @Override public List<E> subList(int fromIndex, int toIndex) { while ((fromIndex >= items.size() || toIndex >= items.size()) && hasNextPage()) { loadNextPage(); } return items.subList(fromIndex, toIndex); } private void tryLoadToIndex(int index) { while (index >= items.size() && hasNextPage()) { loadNextPage(); } } /** * The implementation of {@link ListIterator} for PagedList. */ private class ListItr implements ListIterator<E> { /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIterator. * * @param index the position in the list to start. */ ListItr(int index) { this.nextIndex = index; } @Override public boolean hasNext() { return this.nextIndex != items.size() || hasNextPage(); } @Override public E next() { if (this.nextIndex >= items.size()) { if (!hasNextPage()) { throw new NoSuchElementException(); } else { loadNextPage(); } return next(); } else { try { E nextItem = items.get(this.nextIndex); this.lastRetIndex = this.nextIndex; this.nextIndex = this.nextIndex + 1; return nextItem; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void remove() { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public boolean hasPrevious() { return this.nextIndex != 0; } @Override public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw new NoSuchElementException(); } else if (i >= items.size()) { throw new ConcurrentModificationException(); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetIndex); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public int nextIndex() { return this.nextIndex; } @Override public int previousIndex() { return this.nextIndex - 1; } @Override public void set(E e) { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.set(this.lastRetIndex, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void add(E e) { try { items.add(this.nextIndex, e); this.nextIndex = this.nextIndex + 1; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } }
Any reason `/path` is required?
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: }
return new URL("http:
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is it is of the format * "&lt;host&gt;:&lt;port&gt;". * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); } }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); } }
Does this issue affect Queues as well? I know it also supports IP-style URLs in Azurite.
public BlobUrlParts setHost(String host) { this.host = host; try { this.isIpUrl = ModelHelper.determineAuthorityIsIpStyle(host); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + host)); } return this; }
}
public BlobUrlParts setHost(String host) { this.host = host; try { this.isIpUrl = ModelHelper.determineAuthorityIsIpStyle(host); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + host)); } return this; }
class BlobUrlParts { private final ClientLogger logger = new ClientLogger(BlobUrlParts.class); private String scheme; private String host; private String containerName; private String blobName; private String snapshot; private String accountName; private boolean isIpUrl; private CommonSasQueryParameters commonSasQueryParameters; private Map<String, String[]> unparsedParameters; /** * Initializes a BlobUrlParts object which helps aid in the construction of a Blob Storage URL. */ public BlobUrlParts() { unparsedParameters = new HashMap<>(); } /** * Gets the accountname, ex. "myaccountname". * * @return the account name. */ public String getAccountName() { return accountName; } /** * Sets the account name. * * @param accountName The account name. * @return the updated BlobURLParts object. */ public BlobUrlParts setAccountName(String accountName) { this.accountName = accountName; return this; } /** * Gets the URL scheme, ex. "https: * * @return the URL scheme. */ public String getScheme() { return scheme; } /** * Sets the URL scheme, ex. "https: * * @param scheme The URL scheme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setScheme(String scheme) { this.scheme = scheme; return this; } /** * Gets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @return the URL host. */ public String getHost() { return host; } /** * Sets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @param host The URL host. * @return the updated BlobUrlParts object. */ /** * Gets the container name that will be used as part of the URL path. * * @return the container name. */ public String getBlobContainerName() { return containerName; } /** * Sets the container name that will be used as part of the URL path. * * @param containerName The container nme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setContainerName(String containerName) { this.containerName = containerName; return this; } /** * Decodes and gets the blob name that will be used as part of the URL path. * * @return the decoded blob name. */ public String getBlobName() { return (blobName == null) ? null : Utility.urlDecode(blobName); } /** * Sets the blob name that will be used as part of the URL path. * * @param blobName The blob name. * @return the updated BlobUrlParts object. */ public BlobUrlParts setBlobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(blobName)); return this; } /** * Gets the snapshot identifier that will be used as part of the query string if set. * * @return the snapshot identifier. */ public String getSnapshot() { return snapshot; } /** * Sets the snapshot identifier that will be used as part of the query string if set. * * @param snapshot The snapshot identifier. * @return the updated BlobUrlParts object. */ public BlobUrlParts setSnapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Gets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters * * @return the {@link BlobServiceSasQueryParameters} of the URL * @deprecated Please use {@link */ @Deprecated public BlobServiceSasQueryParameters getSasQueryParameters() { String encodedSas = commonSasQueryParameters.encode(); return new BlobServiceSasQueryParameters(parseQueryString(encodedSas), true); } /** * Sets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters. * * @param blobServiceSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. * @deprecated Please use {@link */ @Deprecated public BlobUrlParts setSasQueryParameters(BlobServiceSasQueryParameters blobServiceSasQueryParameters) { String encodedBlobSas = blobServiceSasQueryParameters.encode(); this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(encodedBlobSas), true); return this; } /** * Gets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @return the {@link CommonSasQueryParameters} of the URL */ public CommonSasQueryParameters getCommonSasQueryParameters() { return commonSasQueryParameters; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param commonSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. */ public BlobUrlParts setCommonSasQueryParameters(CommonSasQueryParameters commonSasQueryParameters) { this.commonSasQueryParameters = commonSasQueryParameters; return this; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param queryParams The SAS query parameter string. * @return the updated BlobUrlParts object. */ public BlobUrlParts parseSasQueryParameters(String queryParams) { this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(queryParams), true); return this; } /** * Gets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @return the non-SAS token query string values. */ public Map<String, String[]> getUnparsedParameters() { return unparsedParameters; } /** * Sets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @param unparsedParameters The non-SAS token query string values. * @return the updated BlobUrlParts object. */ public BlobUrlParts setUnparsedParameters(Map<String, String[]> unparsedParameters) { this.unparsedParameters = unparsedParameters; return this; } /** * Converts the blob URL parts to a {@link URL}. * * @return A {@code URL} to the blob resource composed of all the elements in this object. * @throws IllegalStateException The fields present on the BlobUrlParts object were insufficient to construct a * valid URL or were ill-formatted. */ public URL toUrl() { UrlBuilder url = new UrlBuilder().setScheme(this.scheme).setHost(this.host); StringBuilder path = new StringBuilder(); if (CoreUtils.isNullOrEmpty(this.containerName) && this.blobName != null) { this.containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } if (this.isIpUrl) { path.append(this.accountName); } if (this.containerName != null) { path.append("/").append(this.containerName); if (this.blobName != null) { path.append("/").append(this.blobName); } } url.setPath(path.toString()); if (this.snapshot != null) { url.setQueryParameter(Constants.UrlConstants.SNAPSHOT_QUERY_PARAMETER, this.snapshot); } if (this.commonSasQueryParameters != null) { String encodedSAS = this.commonSasQueryParameters.encode(); if (encodedSAS.length() != 0) { url.setQuery(encodedSAS); } } for (Map.Entry<String, String[]> entry : this.unparsedParameters.entrySet()) { url.setQueryParameter(entry.getKey(), Utility.urlEncode(String.join(",", entry.getValue()))); } try { return url.toUrl(); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalStateException("The URL parts created a malformed URL.", ex)); } } /** * Parses a string into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. * @throws IllegalArgumentException If {@code url} is a malformed {@link URL}. */ public static BlobUrlParts parse(String url) { try { return parse(new URL(url)); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL format. URL: " + url); } } /** * Parses an existing URL into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. */ public static BlobUrlParts parse(URL url) { BlobUrlParts parts = new BlobUrlParts().setScheme(url.getProtocol()); try { if (ModelHelper.determineAuthorityIsIpStyle(url.getAuthority())) { parseIpUrl(url, parts); } else { parseNonIpUrl(url, parts); } } catch (MalformedURLException e) { throw parts.logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + url.getAuthority())); } Map<String, String[]> queryParamsMap = parseQueryString(url.getQuery()); String[] snapshotArray = queryParamsMap.remove("snapshot"); if (snapshotArray != null) { parts.setSnapshot(snapshotArray[0]); } CommonSasQueryParameters commonSasQueryParameters = new CommonSasQueryParameters(queryParamsMap, true); return parts.setCommonSasQueryParameters(commonSasQueryParameters) .setUnparsedParameters(queryParamsMap); } /* * Parse the IP url into its host, account name, container name, and blob name. */ private static void parseIpUrl(URL url, BlobUrlParts parts) { parts.setHost(url.getAuthority()); String path = url.getPath(); if (path.charAt(0) == '/') { path = path.substring(1); } String[] pathPieces = path.split("/", 3); parts.setAccountName(pathPieces[0]); if (pathPieces.length >= 3) { parts.setContainerName(pathPieces[1]); parts.setBlobName(pathPieces[2]); } else if (pathPieces.length == 2) { parts.setContainerName(pathPieces[1]); } parts.isIpUrl = true; } /* * Parse the non-IP url into its host, account name, container name, and blob name. */ private static void parseNonIpUrl(URL url, BlobUrlParts parts) { String host = url.getHost(); parts.setHost(host); if (!CoreUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { parts.setAccountName(host); } else { parts.setAccountName(host.substring(0, accountNameIndex)); } } String path = url.getPath(); if (!CoreUtils.isNullOrEmpty(path)) { if (path.charAt(0) == '/') { path = path.substring(1); } int containerEndIndex = path.indexOf('/'); if (containerEndIndex == -1) { parts.setContainerName(path); } else { parts.setContainerName(path.substring(0, containerEndIndex)); parts.setBlobName(path.substring(containerEndIndex + 1)); } } parts.isIpUrl = false; } /** * Parses a query string into a one to many TreeMap. * * @param queryParams The string of query params to parse. * @return A {@code HashMap<String, String[]>} of the key values. */ private static TreeMap<String, String[]> parseQueryString(String queryParams) { final TreeMap<String, String[]> retVals = new TreeMap<>(Comparator.naturalOrder()); if (CoreUtils.isNullOrEmpty(queryParams)) { return retVals; } final String[] valuePairs = queryParams.split("&"); for (String valuePair : valuePairs) { final int equalDex = valuePair.indexOf("="); String key = Utility.urlDecode(valuePair.substring(0, equalDex)).toLowerCase(Locale.ROOT); String value = Utility.urlDecode(valuePair.substring(equalDex + 1)); String[] keyValues = retVals.get(key); if (keyValues == null) { keyValues = new String[]{value}; } else { final String[] newValues = new String[keyValues.length + 1]; System.arraycopy(keyValues, 0, newValues, 0, keyValues.length); newValues[newValues.length - 1] = value; keyValues = newValues; } retVals.put(key, keyValues); } return retVals; } }
class BlobUrlParts { private final ClientLogger logger = new ClientLogger(BlobUrlParts.class); private String scheme; private String host; private String containerName; private String blobName; private String snapshot; private String accountName; private boolean isIpUrl; private CommonSasQueryParameters commonSasQueryParameters; private Map<String, String[]> unparsedParameters; /** * Initializes a BlobUrlParts object which helps aid in the construction of a Blob Storage URL. */ public BlobUrlParts() { unparsedParameters = new HashMap<>(); } /** * Gets the accountname, ex. "myaccountname". * * @return the account name. */ public String getAccountName() { return accountName; } /** * Sets the account name. * * @param accountName The account name. * @return the updated BlobURLParts object. */ public BlobUrlParts setAccountName(String accountName) { this.accountName = accountName; return this; } /** * Gets the URL scheme, ex. "https: * * @return the URL scheme. */ public String getScheme() { return scheme; } /** * Sets the URL scheme, ex. "https: * * @param scheme The URL scheme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setScheme(String scheme) { this.scheme = scheme; return this; } /** * Gets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @return the URL host. */ public String getHost() { return host; } /** * Sets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @param host The URL host. * @return the updated BlobUrlParts object. */ /** * Gets the container name that will be used as part of the URL path. * * @return the container name. */ public String getBlobContainerName() { return containerName; } /** * Sets the container name that will be used as part of the URL path. * * @param containerName The container nme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setContainerName(String containerName) { this.containerName = containerName; return this; } /** * Decodes and gets the blob name that will be used as part of the URL path. * * @return the decoded blob name. */ public String getBlobName() { return (blobName == null) ? null : Utility.urlDecode(blobName); } /** * Sets the blob name that will be used as part of the URL path. * * @param blobName The blob name. * @return the updated BlobUrlParts object. */ public BlobUrlParts setBlobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(blobName)); return this; } /** * Gets the snapshot identifier that will be used as part of the query string if set. * * @return the snapshot identifier. */ public String getSnapshot() { return snapshot; } /** * Sets the snapshot identifier that will be used as part of the query string if set. * * @param snapshot The snapshot identifier. * @return the updated BlobUrlParts object. */ public BlobUrlParts setSnapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Gets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters * * @return the {@link BlobServiceSasQueryParameters} of the URL * @deprecated Please use {@link */ @Deprecated public BlobServiceSasQueryParameters getSasQueryParameters() { String encodedSas = commonSasQueryParameters.encode(); return new BlobServiceSasQueryParameters(parseQueryString(encodedSas), true); } /** * Sets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters. * * @param blobServiceSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. * @deprecated Please use {@link */ @Deprecated public BlobUrlParts setSasQueryParameters(BlobServiceSasQueryParameters blobServiceSasQueryParameters) { String encodedBlobSas = blobServiceSasQueryParameters.encode(); this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(encodedBlobSas), true); return this; } /** * Gets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @return the {@link CommonSasQueryParameters} of the URL */ public CommonSasQueryParameters getCommonSasQueryParameters() { return commonSasQueryParameters; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param commonSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. */ public BlobUrlParts setCommonSasQueryParameters(CommonSasQueryParameters commonSasQueryParameters) { this.commonSasQueryParameters = commonSasQueryParameters; return this; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param queryParams The SAS query parameter string. * @return the updated BlobUrlParts object. */ public BlobUrlParts parseSasQueryParameters(String queryParams) { this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(queryParams), true); return this; } /** * Gets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @return the non-SAS token query string values. */ public Map<String, String[]> getUnparsedParameters() { return unparsedParameters; } /** * Sets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @param unparsedParameters The non-SAS token query string values. * @return the updated BlobUrlParts object. */ public BlobUrlParts setUnparsedParameters(Map<String, String[]> unparsedParameters) { this.unparsedParameters = unparsedParameters; return this; } /** * Converts the blob URL parts to a {@link URL}. * * @return A {@code URL} to the blob resource composed of all the elements in this object. * @throws IllegalStateException The fields present on the BlobUrlParts object were insufficient to construct a * valid URL or were ill-formatted. */ public URL toUrl() { UrlBuilder url = new UrlBuilder().setScheme(this.scheme).setHost(this.host); StringBuilder path = new StringBuilder(); if (CoreUtils.isNullOrEmpty(this.containerName) && this.blobName != null) { this.containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } if (this.isIpUrl) { path.append(this.accountName); } if (this.containerName != null) { path.append("/").append(this.containerName); if (this.blobName != null) { path.append("/").append(this.blobName); } } url.setPath(path.toString()); if (this.snapshot != null) { url.setQueryParameter(Constants.UrlConstants.SNAPSHOT_QUERY_PARAMETER, this.snapshot); } if (this.commonSasQueryParameters != null) { String encodedSAS = this.commonSasQueryParameters.encode(); if (encodedSAS.length() != 0) { url.setQuery(encodedSAS); } } for (Map.Entry<String, String[]> entry : this.unparsedParameters.entrySet()) { url.setQueryParameter(entry.getKey(), Utility.urlEncode(String.join(",", entry.getValue()))); } try { return url.toUrl(); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalStateException("The URL parts created a malformed URL.", ex)); } } /** * Parses a string into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. * @throws IllegalArgumentException If {@code url} is a malformed {@link URL}. */ public static BlobUrlParts parse(String url) { try { return parse(new URL(url)); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL format. URL: " + url); } } /** * Parses an existing URL into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. */ public static BlobUrlParts parse(URL url) { BlobUrlParts parts = new BlobUrlParts().setScheme(url.getProtocol()); try { if (ModelHelper.determineAuthorityIsIpStyle(url.getAuthority())) { parseIpUrl(url, parts); } else { parseNonIpUrl(url, parts); } } catch (MalformedURLException e) { throw parts.logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + url.getAuthority())); } Map<String, String[]> queryParamsMap = parseQueryString(url.getQuery()); String[] snapshotArray = queryParamsMap.remove("snapshot"); if (snapshotArray != null) { parts.setSnapshot(snapshotArray[0]); } CommonSasQueryParameters commonSasQueryParameters = new CommonSasQueryParameters(queryParamsMap, true); return parts.setCommonSasQueryParameters(commonSasQueryParameters) .setUnparsedParameters(queryParamsMap); } /* * Parse the IP url into its host, account name, container name, and blob name. */ private static void parseIpUrl(URL url, BlobUrlParts parts) { parts.setHost(url.getAuthority()); String path = url.getPath(); if (path.charAt(0) == '/') { path = path.substring(1); } String[] pathPieces = path.split("/", 3); parts.setAccountName(pathPieces[0]); if (pathPieces.length >= 3) { parts.setContainerName(pathPieces[1]); parts.setBlobName(pathPieces[2]); } else if (pathPieces.length == 2) { parts.setContainerName(pathPieces[1]); } parts.isIpUrl = true; } /* * Parse the non-IP url into its host, account name, container name, and blob name. */ private static void parseNonIpUrl(URL url, BlobUrlParts parts) { String host = url.getHost(); parts.setHost(host); if (!CoreUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { parts.setAccountName(host); } else { parts.setAccountName(host.substring(0, accountNameIndex)); } } String path = url.getPath(); if (!CoreUtils.isNullOrEmpty(path)) { if (path.charAt(0) == '/') { path = path.substring(1); } int containerEndIndex = path.indexOf('/'); if (containerEndIndex == -1) { parts.setContainerName(path); } else { parts.setContainerName(path.substring(0, containerEndIndex)); parts.setBlobName(path.substring(containerEndIndex + 1)); } } parts.isIpUrl = false; } /** * Parses a query string into a one to many TreeMap. * * @param queryParams The string of query params to parse. * @return A {@code HashMap<String, String[]>} of the key values. */ private static TreeMap<String, String[]> parseQueryString(String queryParams) { final TreeMap<String, String[]> retVals = new TreeMap<>(Comparator.naturalOrder()); if (CoreUtils.isNullOrEmpty(queryParams)) { return retVals; } final String[] valuePairs = queryParams.split("&"); for (String valuePair : valuePairs) { final int equalDex = valuePair.indexOf("="); String key = Utility.urlDecode(valuePair.substring(0, equalDex)).toLowerCase(Locale.ROOT); String value = Utility.urlDecode(valuePair.substring(equalDex + 1)); String[] keyValues = retVals.get(key); if (keyValues == null) { keyValues = new String[]{value}; } else { final String[] newValues = new String[keyValues.length + 1]; System.arraycopy(keyValues, 0, newValues, 0, keyValues.length); newValues[newValues.length - 1] = value; keyValues = newValues; } retVals.put(key, keyValues); } return retVals; } }
It was a required parameter for an overload of URL constructor that I was initially trying to use, but I can try this without it and see if it still works
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: }
return new URL("http:
public static boolean determineAuthorityIsIpStyle(String authority) throws MalformedURLException { return new URL("http: }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is it is of the format * "&lt;host&gt;:&lt;port&gt;". * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); } }
class ModelHelper { /** * Determines whether or not the passed authority is IP style, that is, it is of the format {@code <host>:<port>}. * * @param authority The authority of a URL. * @throws MalformedURLException If the authority is malformed. * @return Whether the authority is IP style. */ /** * Fills in default values for a ParallelTransferOptions where no value has been set. This will construct a new * object for safety. * * @param other The options to fill in defaults. * @return An object with defaults filled in for null values in the original. */ public static ParallelTransferOptions populateAndApplyDefaults(ParallelTransferOptions other) { other = other == null ? new ParallelTransferOptions(null, null, null) : other; return new ParallelTransferOptions( other.getBlockSize() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_UPLOAD_BLOCK_SIZE) : other.getBlockSize(), other.getNumBuffers() == null ? Integer.valueOf(BlobAsyncClient.BLOB_DEFAULT_NUMBER_OF_BUFFERS) : other.getNumBuffers(), other.getProgressReceiver(), other.getMaxSingleUploadSize() == null ? Integer.valueOf(BlockBlobAsyncClient.MAX_UPLOAD_BLOB_BYTES) : other.getMaxSingleUploadSize()); } }
Yea I should probably bring it over there as well. Thanks for thinking of that.
public BlobUrlParts setHost(String host) { this.host = host; try { this.isIpUrl = ModelHelper.determineAuthorityIsIpStyle(host); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + host)); } return this; }
}
public BlobUrlParts setHost(String host) { this.host = host; try { this.isIpUrl = ModelHelper.determineAuthorityIsIpStyle(host); } catch (MalformedURLException e) { throw logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + host)); } return this; }
class BlobUrlParts { private final ClientLogger logger = new ClientLogger(BlobUrlParts.class); private String scheme; private String host; private String containerName; private String blobName; private String snapshot; private String accountName; private boolean isIpUrl; private CommonSasQueryParameters commonSasQueryParameters; private Map<String, String[]> unparsedParameters; /** * Initializes a BlobUrlParts object which helps aid in the construction of a Blob Storage URL. */ public BlobUrlParts() { unparsedParameters = new HashMap<>(); } /** * Gets the accountname, ex. "myaccountname". * * @return the account name. */ public String getAccountName() { return accountName; } /** * Sets the account name. * * @param accountName The account name. * @return the updated BlobURLParts object. */ public BlobUrlParts setAccountName(String accountName) { this.accountName = accountName; return this; } /** * Gets the URL scheme, ex. "https: * * @return the URL scheme. */ public String getScheme() { return scheme; } /** * Sets the URL scheme, ex. "https: * * @param scheme The URL scheme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setScheme(String scheme) { this.scheme = scheme; return this; } /** * Gets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @return the URL host. */ public String getHost() { return host; } /** * Sets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @param host The URL host. * @return the updated BlobUrlParts object. */ /** * Gets the container name that will be used as part of the URL path. * * @return the container name. */ public String getBlobContainerName() { return containerName; } /** * Sets the container name that will be used as part of the URL path. * * @param containerName The container nme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setContainerName(String containerName) { this.containerName = containerName; return this; } /** * Decodes and gets the blob name that will be used as part of the URL path. * * @return the decoded blob name. */ public String getBlobName() { return (blobName == null) ? null : Utility.urlDecode(blobName); } /** * Sets the blob name that will be used as part of the URL path. * * @param blobName The blob name. * @return the updated BlobUrlParts object. */ public BlobUrlParts setBlobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(blobName)); return this; } /** * Gets the snapshot identifier that will be used as part of the query string if set. * * @return the snapshot identifier. */ public String getSnapshot() { return snapshot; } /** * Sets the snapshot identifier that will be used as part of the query string if set. * * @param snapshot The snapshot identifier. * @return the updated BlobUrlParts object. */ public BlobUrlParts setSnapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Gets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters * * @return the {@link BlobServiceSasQueryParameters} of the URL * @deprecated Please use {@link */ @Deprecated public BlobServiceSasQueryParameters getSasQueryParameters() { String encodedSas = commonSasQueryParameters.encode(); return new BlobServiceSasQueryParameters(parseQueryString(encodedSas), true); } /** * Sets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters. * * @param blobServiceSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. * @deprecated Please use {@link */ @Deprecated public BlobUrlParts setSasQueryParameters(BlobServiceSasQueryParameters blobServiceSasQueryParameters) { String encodedBlobSas = blobServiceSasQueryParameters.encode(); this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(encodedBlobSas), true); return this; } /** * Gets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @return the {@link CommonSasQueryParameters} of the URL */ public CommonSasQueryParameters getCommonSasQueryParameters() { return commonSasQueryParameters; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param commonSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. */ public BlobUrlParts setCommonSasQueryParameters(CommonSasQueryParameters commonSasQueryParameters) { this.commonSasQueryParameters = commonSasQueryParameters; return this; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param queryParams The SAS query parameter string. * @return the updated BlobUrlParts object. */ public BlobUrlParts parseSasQueryParameters(String queryParams) { this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(queryParams), true); return this; } /** * Gets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @return the non-SAS token query string values. */ public Map<String, String[]> getUnparsedParameters() { return unparsedParameters; } /** * Sets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @param unparsedParameters The non-SAS token query string values. * @return the updated BlobUrlParts object. */ public BlobUrlParts setUnparsedParameters(Map<String, String[]> unparsedParameters) { this.unparsedParameters = unparsedParameters; return this; } /** * Converts the blob URL parts to a {@link URL}. * * @return A {@code URL} to the blob resource composed of all the elements in this object. * @throws IllegalStateException The fields present on the BlobUrlParts object were insufficient to construct a * valid URL or were ill-formatted. */ public URL toUrl() { UrlBuilder url = new UrlBuilder().setScheme(this.scheme).setHost(this.host); StringBuilder path = new StringBuilder(); if (CoreUtils.isNullOrEmpty(this.containerName) && this.blobName != null) { this.containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } if (this.isIpUrl) { path.append(this.accountName); } if (this.containerName != null) { path.append("/").append(this.containerName); if (this.blobName != null) { path.append("/").append(this.blobName); } } url.setPath(path.toString()); if (this.snapshot != null) { url.setQueryParameter(Constants.UrlConstants.SNAPSHOT_QUERY_PARAMETER, this.snapshot); } if (this.commonSasQueryParameters != null) { String encodedSAS = this.commonSasQueryParameters.encode(); if (encodedSAS.length() != 0) { url.setQuery(encodedSAS); } } for (Map.Entry<String, String[]> entry : this.unparsedParameters.entrySet()) { url.setQueryParameter(entry.getKey(), Utility.urlEncode(String.join(",", entry.getValue()))); } try { return url.toUrl(); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalStateException("The URL parts created a malformed URL.", ex)); } } /** * Parses a string into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. * @throws IllegalArgumentException If {@code url} is a malformed {@link URL}. */ public static BlobUrlParts parse(String url) { try { return parse(new URL(url)); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL format. URL: " + url); } } /** * Parses an existing URL into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. */ public static BlobUrlParts parse(URL url) { BlobUrlParts parts = new BlobUrlParts().setScheme(url.getProtocol()); try { if (ModelHelper.determineAuthorityIsIpStyle(url.getAuthority())) { parseIpUrl(url, parts); } else { parseNonIpUrl(url, parts); } } catch (MalformedURLException e) { throw parts.logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + url.getAuthority())); } Map<String, String[]> queryParamsMap = parseQueryString(url.getQuery()); String[] snapshotArray = queryParamsMap.remove("snapshot"); if (snapshotArray != null) { parts.setSnapshot(snapshotArray[0]); } CommonSasQueryParameters commonSasQueryParameters = new CommonSasQueryParameters(queryParamsMap, true); return parts.setCommonSasQueryParameters(commonSasQueryParameters) .setUnparsedParameters(queryParamsMap); } /* * Parse the IP url into its host, account name, container name, and blob name. */ private static void parseIpUrl(URL url, BlobUrlParts parts) { parts.setHost(url.getAuthority()); String path = url.getPath(); if (path.charAt(0) == '/') { path = path.substring(1); } String[] pathPieces = path.split("/", 3); parts.setAccountName(pathPieces[0]); if (pathPieces.length >= 3) { parts.setContainerName(pathPieces[1]); parts.setBlobName(pathPieces[2]); } else if (pathPieces.length == 2) { parts.setContainerName(pathPieces[1]); } parts.isIpUrl = true; } /* * Parse the non-IP url into its host, account name, container name, and blob name. */ private static void parseNonIpUrl(URL url, BlobUrlParts parts) { String host = url.getHost(); parts.setHost(host); if (!CoreUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { parts.setAccountName(host); } else { parts.setAccountName(host.substring(0, accountNameIndex)); } } String path = url.getPath(); if (!CoreUtils.isNullOrEmpty(path)) { if (path.charAt(0) == '/') { path = path.substring(1); } int containerEndIndex = path.indexOf('/'); if (containerEndIndex == -1) { parts.setContainerName(path); } else { parts.setContainerName(path.substring(0, containerEndIndex)); parts.setBlobName(path.substring(containerEndIndex + 1)); } } parts.isIpUrl = false; } /** * Parses a query string into a one to many TreeMap. * * @param queryParams The string of query params to parse. * @return A {@code HashMap<String, String[]>} of the key values. */ private static TreeMap<String, String[]> parseQueryString(String queryParams) { final TreeMap<String, String[]> retVals = new TreeMap<>(Comparator.naturalOrder()); if (CoreUtils.isNullOrEmpty(queryParams)) { return retVals; } final String[] valuePairs = queryParams.split("&"); for (String valuePair : valuePairs) { final int equalDex = valuePair.indexOf("="); String key = Utility.urlDecode(valuePair.substring(0, equalDex)).toLowerCase(Locale.ROOT); String value = Utility.urlDecode(valuePair.substring(equalDex + 1)); String[] keyValues = retVals.get(key); if (keyValues == null) { keyValues = new String[]{value}; } else { final String[] newValues = new String[keyValues.length + 1]; System.arraycopy(keyValues, 0, newValues, 0, keyValues.length); newValues[newValues.length - 1] = value; keyValues = newValues; } retVals.put(key, keyValues); } return retVals; } }
class BlobUrlParts { private final ClientLogger logger = new ClientLogger(BlobUrlParts.class); private String scheme; private String host; private String containerName; private String blobName; private String snapshot; private String accountName; private boolean isIpUrl; private CommonSasQueryParameters commonSasQueryParameters; private Map<String, String[]> unparsedParameters; /** * Initializes a BlobUrlParts object which helps aid in the construction of a Blob Storage URL. */ public BlobUrlParts() { unparsedParameters = new HashMap<>(); } /** * Gets the accountname, ex. "myaccountname". * * @return the account name. */ public String getAccountName() { return accountName; } /** * Sets the account name. * * @param accountName The account name. * @return the updated BlobURLParts object. */ public BlobUrlParts setAccountName(String accountName) { this.accountName = accountName; return this; } /** * Gets the URL scheme, ex. "https: * * @return the URL scheme. */ public String getScheme() { return scheme; } /** * Sets the URL scheme, ex. "https: * * @param scheme The URL scheme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setScheme(String scheme) { this.scheme = scheme; return this; } /** * Gets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @return the URL host. */ public String getHost() { return host; } /** * Sets the URL host, ex. "account.blob.core.windows.net" or "127.0.0.1:10000". * * @param host The URL host. * @return the updated BlobUrlParts object. */ /** * Gets the container name that will be used as part of the URL path. * * @return the container name. */ public String getBlobContainerName() { return containerName; } /** * Sets the container name that will be used as part of the URL path. * * @param containerName The container nme. * @return the updated BlobUrlParts object. */ public BlobUrlParts setContainerName(String containerName) { this.containerName = containerName; return this; } /** * Decodes and gets the blob name that will be used as part of the URL path. * * @return the decoded blob name. */ public String getBlobName() { return (blobName == null) ? null : Utility.urlDecode(blobName); } /** * Sets the blob name that will be used as part of the URL path. * * @param blobName The blob name. * @return the updated BlobUrlParts object. */ public BlobUrlParts setBlobName(String blobName) { this.blobName = Utility.urlEncode(Utility.urlDecode(blobName)); return this; } /** * Gets the snapshot identifier that will be used as part of the query string if set. * * @return the snapshot identifier. */ public String getSnapshot() { return snapshot; } /** * Sets the snapshot identifier that will be used as part of the query string if set. * * @param snapshot The snapshot identifier. * @return the updated BlobUrlParts object. */ public BlobUrlParts setSnapshot(String snapshot) { this.snapshot = snapshot; return this; } /** * Gets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters * * @return the {@link BlobServiceSasQueryParameters} of the URL * @deprecated Please use {@link */ @Deprecated public BlobServiceSasQueryParameters getSasQueryParameters() { String encodedSas = commonSasQueryParameters.encode(); return new BlobServiceSasQueryParameters(parseQueryString(encodedSas), true); } /** * Sets the {@link BlobServiceSasQueryParameters} representing the SAS query parameters. * * @param blobServiceSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. * @deprecated Please use {@link */ @Deprecated public BlobUrlParts setSasQueryParameters(BlobServiceSasQueryParameters blobServiceSasQueryParameters) { String encodedBlobSas = blobServiceSasQueryParameters.encode(); this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(encodedBlobSas), true); return this; } /** * Gets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @return the {@link CommonSasQueryParameters} of the URL */ public CommonSasQueryParameters getCommonSasQueryParameters() { return commonSasQueryParameters; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param commonSasQueryParameters The SAS query parameters. * @return the updated BlobUrlParts object. */ public BlobUrlParts setCommonSasQueryParameters(CommonSasQueryParameters commonSasQueryParameters) { this.commonSasQueryParameters = commonSasQueryParameters; return this; } /** * Sets the {@link CommonSasQueryParameters} representing the SAS query parameters that will be used to * generate the SAS token for this URL. * * @param queryParams The SAS query parameter string. * @return the updated BlobUrlParts object. */ public BlobUrlParts parseSasQueryParameters(String queryParams) { this.commonSasQueryParameters = new CommonSasQueryParameters(parseQueryString(queryParams), true); return this; } /** * Gets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @return the non-SAS token query string values. */ public Map<String, String[]> getUnparsedParameters() { return unparsedParameters; } /** * Sets the query string parameters that aren't part of the SAS token that will be used by this URL. * * @param unparsedParameters The non-SAS token query string values. * @return the updated BlobUrlParts object. */ public BlobUrlParts setUnparsedParameters(Map<String, String[]> unparsedParameters) { this.unparsedParameters = unparsedParameters; return this; } /** * Converts the blob URL parts to a {@link URL}. * * @return A {@code URL} to the blob resource composed of all the elements in this object. * @throws IllegalStateException The fields present on the BlobUrlParts object were insufficient to construct a * valid URL or were ill-formatted. */ public URL toUrl() { UrlBuilder url = new UrlBuilder().setScheme(this.scheme).setHost(this.host); StringBuilder path = new StringBuilder(); if (CoreUtils.isNullOrEmpty(this.containerName) && this.blobName != null) { this.containerName = BlobContainerAsyncClient.ROOT_CONTAINER_NAME; } if (this.isIpUrl) { path.append(this.accountName); } if (this.containerName != null) { path.append("/").append(this.containerName); if (this.blobName != null) { path.append("/").append(this.blobName); } } url.setPath(path.toString()); if (this.snapshot != null) { url.setQueryParameter(Constants.UrlConstants.SNAPSHOT_QUERY_PARAMETER, this.snapshot); } if (this.commonSasQueryParameters != null) { String encodedSAS = this.commonSasQueryParameters.encode(); if (encodedSAS.length() != 0) { url.setQuery(encodedSAS); } } for (Map.Entry<String, String[]> entry : this.unparsedParameters.entrySet()) { url.setQueryParameter(entry.getKey(), Utility.urlEncode(String.join(",", entry.getValue()))); } try { return url.toUrl(); } catch (MalformedURLException ex) { throw logger.logExceptionAsError(new IllegalStateException("The URL parts created a malformed URL.", ex)); } } /** * Parses a string into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. * @throws IllegalArgumentException If {@code url} is a malformed {@link URL}. */ public static BlobUrlParts parse(String url) { try { return parse(new URL(url)); } catch (MalformedURLException e) { throw new IllegalArgumentException("Invalid URL format. URL: " + url); } } /** * Parses an existing URL into a BlobUrlParts. * * <p>Query parameters will be parsed into two properties, {@link BlobServiceSasQueryParameters} which contains * all SAS token related values and {@link * parameters.</p> * * <p>If a URL points to a blob in the root container, and the root container is referenced implicitly, i.e. there * is no path element for the container, the name of this blob in the root container will be set as the * containerName field in the resulting {@code BlobURLParts}.</p> * * @param url The {@code URL} to be parsed. * @return A {@link BlobUrlParts} object containing all the components of a BlobURL. */ public static BlobUrlParts parse(URL url) { BlobUrlParts parts = new BlobUrlParts().setScheme(url.getProtocol()); try { if (ModelHelper.determineAuthorityIsIpStyle(url.getAuthority())) { parseIpUrl(url, parts); } else { parseNonIpUrl(url, parts); } } catch (MalformedURLException e) { throw parts.logger.logExceptionAsError(new IllegalStateException("Authority is malformed. Host: " + url.getAuthority())); } Map<String, String[]> queryParamsMap = parseQueryString(url.getQuery()); String[] snapshotArray = queryParamsMap.remove("snapshot"); if (snapshotArray != null) { parts.setSnapshot(snapshotArray[0]); } CommonSasQueryParameters commonSasQueryParameters = new CommonSasQueryParameters(queryParamsMap, true); return parts.setCommonSasQueryParameters(commonSasQueryParameters) .setUnparsedParameters(queryParamsMap); } /* * Parse the IP url into its host, account name, container name, and blob name. */ private static void parseIpUrl(URL url, BlobUrlParts parts) { parts.setHost(url.getAuthority()); String path = url.getPath(); if (path.charAt(0) == '/') { path = path.substring(1); } String[] pathPieces = path.split("/", 3); parts.setAccountName(pathPieces[0]); if (pathPieces.length >= 3) { parts.setContainerName(pathPieces[1]); parts.setBlobName(pathPieces[2]); } else if (pathPieces.length == 2) { parts.setContainerName(pathPieces[1]); } parts.isIpUrl = true; } /* * Parse the non-IP url into its host, account name, container name, and blob name. */ private static void parseNonIpUrl(URL url, BlobUrlParts parts) { String host = url.getHost(); parts.setHost(host); if (!CoreUtils.isNullOrEmpty(host)) { int accountNameIndex = host.indexOf('.'); if (accountNameIndex == -1) { parts.setAccountName(host); } else { parts.setAccountName(host.substring(0, accountNameIndex)); } } String path = url.getPath(); if (!CoreUtils.isNullOrEmpty(path)) { if (path.charAt(0) == '/') { path = path.substring(1); } int containerEndIndex = path.indexOf('/'); if (containerEndIndex == -1) { parts.setContainerName(path); } else { parts.setContainerName(path.substring(0, containerEndIndex)); parts.setBlobName(path.substring(containerEndIndex + 1)); } } parts.isIpUrl = false; } /** * Parses a query string into a one to many TreeMap. * * @param queryParams The string of query params to parse. * @return A {@code HashMap<String, String[]>} of the key values. */ private static TreeMap<String, String[]> parseQueryString(String queryParams) { final TreeMap<String, String[]> retVals = new TreeMap<>(Comparator.naturalOrder()); if (CoreUtils.isNullOrEmpty(queryParams)) { return retVals; } final String[] valuePairs = queryParams.split("&"); for (String valuePair : valuePairs) { final int equalDex = valuePair.indexOf("="); String key = Utility.urlDecode(valuePair.substring(0, equalDex)).toLowerCase(Locale.ROOT); String value = Utility.urlDecode(valuePair.substring(equalDex + 1)); String[] keyValues = retVals.get(key); if (keyValues == null) { keyValues = new String[]{value}; } else { final String[] newValues = new String[keyValues.length + 1]; System.arraycopy(keyValues, 0, newValues, 0, keyValues.length); newValues[newValues.length - 1] = value; keyValues = newValues; } retVals.put(key, keyValues); } return retVals; } }
Track 1: They update same object in this way.
public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage receivedMessage) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(receivedMessage.getLockToken()) .map(instant -> { receivedMessage.setLockedUntil(instant); return instant; })); }
receivedMessage.setLockedUntil(instant);
public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage receivedMessage) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(receivedMessage.getLockToken()) .map(instant -> { receivedMessage.setLockedUntil(instant); return instant; })); }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Autocomplete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param messageLock The {@link UUID} value of the message lock to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Instant> renewMessageLock(UUID messageLock) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(messageLock)); } /** * Asynchronously renews the lock on the specified message. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param receivedMessage to be used to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param fromSequenceNumber The sequence number from where to read the message. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages, fromSequenceNumber)); } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
class ServiceBusReceiverAsyncClient implements Closeable { private final AtomicBoolean isDisposed = new AtomicBoolean(); private final ClientLogger logger = new ClientLogger(ServiceBusReceiverAsyncClient.class); private final ConcurrentHashMap<UUID, Instant> lockTokenExpirationMap = new ConcurrentHashMap<>(); private final String fullyQualifiedNamespace; private final String entityPath; private final MessagingEntityType entityType; private final boolean isSessionEnabled; private final ServiceBusConnectionProcessor connectionProcessor; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; private final Duration maxAutoRenewDuration; private final int prefetch; private final boolean isAutoComplete; private final ReceiveMode receiveMode; /** * Map containing linkNames and their associated consumers. Key: linkName Value: consumer associated with that * linkName. */ private final ConcurrentHashMap<String, ServiceBusAsyncConsumer> openConsumers = new ConcurrentHashMap<>(); ServiceBusReceiverAsyncClient(String fullyQualifiedNamespace, String entityPath, MessagingEntityType entityType, boolean isSessionEnabled, ReceiveMessageOptions receiveMessageOptions, ServiceBusConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer) { this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, "'fullyQualifiedNamespace' cannot be null."); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.connectionProcessor = Objects.requireNonNull(connectionProcessor, "'connectionProcessor' cannot be null."); this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); Objects.requireNonNull(receiveMessageOptions, "'receiveMessageOptions' cannot be null."); this.prefetch = receiveMessageOptions.getPrefetchCount(); this.maxAutoRenewDuration = receiveMessageOptions.getMaxAutoRenewDuration(); this.isAutoComplete = receiveMessageOptions.isAutoComplete(); this.receiveMode = receiveMessageOptions.getReceiveMode(); this.entityType = entityType; this.isSessionEnabled = isSessionEnabled; } /** * Gets the fully qualified Service Bus namespace that the connection is associated with. This is likely similar to * {@code {yournamespace}.servicebus.windows.net}. * * @return The fully qualified Service Bus namespace that the connection is associated with. */ public String getFullyQualifiedNamespace() { return fullyQualifiedNamespace; } /** * Gets the Service Bus resource this client interacts with. * * @return The Service Bus resource this client interacts with. */ public String getServiceBusResourceName() { return entityPath; } /** * Receives a stream of {@link ServiceBusReceivedMessage}. * * @return A stream of messages from Service Bus. */ public Flux<ServiceBusReceivedMessage> receive() { if (isDisposed.get()) { return Flux.error(logger.logExceptionAsError( new IllegalStateException("Cannot receive from a client that is already closed."))); } if (receiveMode != ReceiveMode.PEEK_LOCK && isAutoComplete) { return Flux.error(logger.logExceptionAsError(new UnsupportedOperationException( "Autocomplete is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE."))); } final String linkName = entityPath; return getOrCreateConsumer(entityPath) .receive() .map(message -> { if (message.getLockToken() == null || MessageUtils.ZERO_LOCK_TOKEN.equals(message.getLockToken())) { return message; } lockTokenExpirationMap.compute(message.getLockToken(), (key, existing) -> { if (existing == null) { return message.getLockedUntil(); } else { return existing.isBefore(message.getLockedUntil()) ? message.getLockedUntil() : existing; } }); return message; }) .doOnCancel(() -> removeLink(linkName, SignalType.CANCEL)) .doOnComplete(() -> removeLink(linkName, SignalType.ON_COMPLETE)) .doOnError(error -> removeLink(linkName, SignalType.ON_ERROR)); } /** * Abandon {@link ServiceBusMessage} with lock token. This will make the message available again for processing. * Abandoning a message will increase the delivery count on the message. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message) { return abandon(message, null); } /** * Abandon {@link ServiceBusMessage} with lock token and updated message property. This will make the message * available again for processing. Abandoning a message will increase the delivery count on the message. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> abandon(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.ABANDONED, null, null, propertiesToModify); } /** * Completes a {@link ServiceBusMessage} using its lock token. This will delete the message from the service. * * @param message Message to be completed. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> complete(ServiceBusReceivedMessage message) { return updateDisposition(message, DispositionStatus.COMPLETED, null, null, null); } /** * Defers a {@link ServiceBusMessage} using its lock token. This will move message into deferred subqueue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message) { return defer(message, null); } /** * Asynchronously renews the lock on the message specified by the lock token. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param messageLock The {@link UUID} value of the message lock to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Instant> renewMessageLock(UUID messageLock) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(serviceBusManagementNode -> serviceBusManagementNode .renewMessageLock(messageLock)); } /** * Asynchronously renews the lock on the specified message. The lock will be renewed based on the * setting specified on the entity. When a message is received in {@link ReceiveMode * locked on the server for this receiver instance for a duration as specified during the Queue creation * (LockDuration). If processing of the message requires longer than this duration, the lock needs to be renewed. * For each renewal, the lock is reset to the entity's LockDuration value. * * @param receivedMessage to be used to renew. * * @return The {@link Mono} the finishes this operation on service bus resource. */ /** * Defers a {@link ServiceBusMessage} using its lock token with modified message property. This will move message * into deferred subqueue. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> defer(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.DEFERRED, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue. * * @param message to be used. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message) { return deadLetter(message, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with modified message properties. * * @param message to be used. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, Map<String, Object> propertiesToModify) { return deadLetter(message, null, null, propertiesToModify); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason and error description. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription) { return deadLetter(message, deadLetterReason, deadLetterErrorDescription, null); } /** * Moves a {@link ServiceBusMessage} to the deadletter sub-queue with deadletter reason, error description and * modifided properties. * * @param message to be used. * @param deadLetterReason The deadletter reason. * @param deadLetterErrorDescription The deadletter error description. * @param propertiesToModify Message properties to modify. * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<Void> deadLetter(ServiceBusReceivedMessage message, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return updateDisposition(message, DispositionStatus.SUSPENDED, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } /** * Receives a deferred {@link ServiceBusMessage}. Deferred messages can only be received by using sequence number. * * @param sequenceNumber The {@link ServiceBusReceivedMessage * * @return The {@link Mono} the finishes this operation on service bus resource. */ public Mono<ServiceBusReceivedMessage> receiveDeferredMessage(long sequenceNumber) { return null; } /** * Reads the next active message without changing the state of the receiver or the message source. * The first call to {@code peek()} fetches the first active message for * this receiver. Each subsequent call fetches the subsequent message in the entity. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek() { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(ServiceBusManagementNode::peek); } /** * Reads next the active message without changing the state of the receiver or the message source. * * @param fromSequenceNumber The sequence number from where to read the message. * * @return Single {@link ServiceBusReceivedMessage} peeked. */ public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> node.peek(fromSequenceNumber)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages)); } /** * Reads the next batch of active messages without changing the state of the receiver or the message source. * * @param maxMessages The number of messages. * @param fromSequenceNumber The sequence number from where to read the message. * @return The {@link Flux} of {@link ServiceBusReceivedMessage} peeked. */ public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return connectionProcessor .flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMapMany(node -> node.peekBatch(maxMessages, fromSequenceNumber)); } /** * Disposes of the consumer by closing the underlying connection to the service. */ @Override public void close() { if (isDisposed.getAndSet(true)) { return; } final ArrayList<String> keys = new ArrayList<>(openConsumers.keySet()); for (String key : keys) { removeLink(key, SignalType.ON_COMPLETE); } connectionProcessor.dispose(); } private Mono<Boolean> isLockTokenValid(UUID lockToken) { final Instant lockedUntilUtc = lockTokenExpirationMap.get(lockToken); if (lockedUntilUtc == null) { logger.warning("lockToken[{}] is not owned by this receiver.", lockToken); return Mono.just(false); } final Instant now = Instant.now(); if (lockedUntilUtc.isBefore(now)) { return Mono.error(logger.logExceptionAsError(new AmqpException(false, String.format( "Lock already expired for the lock token. Expiration: '%s'. Now: '%s'", lockedUntilUtc, now), getErrorContext()))); } return Mono.just(true); } private Mono<Void> updateDisposition(ServiceBusReceivedMessage message, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { if (message == null) { return Mono.error(new NullPointerException("'message' cannot be null.")); } if (receiveMode != ReceiveMode.PEEK_LOCK) { return Mono.error(logger.logExceptionAsError(new UnsupportedOperationException(String.format( "'%s' is not supported on a receiver opened in ReceiveMode.RECEIVE_AND_DELETE.", dispositionStatus)))); } else if (message.getLockToken() == null) { return Mono.error(logger.logExceptionAsError(new IllegalArgumentException( "'message.getLockToken()' cannot be null."))); } logger.info("{}: Completing message. Sequence number: {}. Lock: {}. Expiration: {}", entityPath, message.getSequenceNumber(), message.getLockToken(), lockTokenExpirationMap.get(message.getLockToken())); return isLockTokenValid(message.getLockToken()).flatMap(isLocked -> { return connectionProcessor.flatMap(connection -> connection.getManagementNode(entityPath, entityType)) .flatMap(node -> { if (isLocked) { return node.updateDisposition(message.getLockToken(), dispositionStatus, deadLetterReason, deadLetterErrorDescription, propertiesToModify); } else { return Mono.error( new UnsupportedOperationException("Cannot complete a message that is not locked.")); } }); }).then(Mono.fromRunnable(() -> lockTokenExpirationMap.remove(message.getLockToken()))); } private ServiceBusAsyncConsumer getOrCreateConsumer(String linkName) { return openConsumers.computeIfAbsent(linkName, name -> { logger.info("{}: Creating consumer for link '{}'", entityPath, linkName); final Flux<AmqpReceiveLink> receiveLink = connectionProcessor.flatMap(connection -> connection.createReceiveLink(linkName, entityPath, receiveMode, isSessionEnabled, null, entityType)) .doOnNext(next -> { final String format = "Created consumer for Service Bus resource: [{}] mode: [{}]" + " sessionEnabled? {} transferEntityPath: [{}], entityType: [{}]"; logger.verbose(format, next.getEntityPath(), receiveMode, isSessionEnabled, "N/A", entityType); }) .repeat(); final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionProcessor.getRetryOptions()); final ServiceBusReceiveLinkProcessor linkMessageProcessor = receiveLink.subscribeWith( new ServiceBusReceiveLinkProcessor(prefetch, retryPolicy, connectionProcessor)); return new ServiceBusAsyncConsumer(linkMessageProcessor, messageSerializer, isAutoComplete, this::complete, this::abandon); }); } private void removeLink(String linkName, SignalType signalType) { logger.info("{}: Receiving completed. Signal[{}]", linkName, signalType); final ServiceBusAsyncConsumer removed = openConsumers.remove(linkName); if (removed != null) { try { removed.close(); } catch (Throwable e) { logger.warning("[{}][{}]: Error occurred while closing consumer '{}'", fullyQualifiedNamespace, entityPath, linkName, e); } } } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(getFullyQualifiedNamespace(), getServiceBusResourceName()); } }
With this, user now have 2 choice when migrate. 1. Use PagedIterable, and refactor any code that handling it. 2. Use PagedList, use it to wrap PagedIterable. Find time later to do all refactor needed in 1.
protected void loadNextPage() { this.items.addAll(pagedResponseIterator.next().getValue()); }
this.items.addAll(pagedResponseIterator.next().getValue());
protected void loadNextPage() { this.items.addAll(pagedResponseIterator.next().getValue()); }
class PagedList<E> implements List<E> { /** The items retrieved. */ private final List<E> items; /** The paged response iterator for not retrieved items. */ private Iterator<PagedResponse<E>> pagedResponseIterator; /** * Creates an instance of PagedList. */ public PagedList() { items = new ArrayList<>(); pagedResponseIterator = Collections.emptyIterator(); } /** * Creates an instance of PagedList from a {@link PagedIterable}. * * @param pagedIterable the {@link PagedIterable} object. */ public PagedList(PagedIterable<E> pagedIterable) { items = new ArrayList<>(); Objects.requireNonNull(pagedIterable, "'pagedIterable' cannot be null."); this.pagedResponseIterator = pagedIterable.iterableByPage().iterator(); } /** * If there are more pages available. * * @return true if there are more pages to load. False otherwise. */ protected boolean hasNextPage() { return pagedResponseIterator.hasNext(); } /** * Loads a page from next page link. * The exceptions are wrapped into Java Runtime exceptions. */ /** * Keep loading the next page from the next page link until all items are loaded. */ public void loadAll() { while (hasNextPage()) { loadNextPage(); } } @Override public int size() { loadAll(); return items.size(); } @Override public boolean isEmpty() { return items.isEmpty() && !hasNextPage(); } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Iterator<E> iterator() { return new ListItr(0); } @Override public Object[] toArray() { loadAll(); return items.toArray(); } @Override public <T> T[] toArray(T[] a) { loadAll(); return items.toArray(a); } @Override public boolean add(E e) { loadAll(); return items.add(e); } @Override public boolean remove(Object o) { int index = indexOf(o); if (index != -1) { items.remove(index); return true; } else { return false; } } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) { if (!contains(e)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends E> c) { return items.addAll(c); } @Override public boolean addAll(int index, Collection<? extends E> c) { return items.addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return items.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return items.retainAll(c); } @Override public void clear() { items.clear(); pagedResponseIterator = Collections.emptyIterator(); } @Override public E get(int index) { tryLoadToIndex(index); return items.get(index); } @Override public E set(int index, E element) { tryLoadToIndex(index); return items.set(index, element); } @Override public void add(int index, E element) { items.add(index, element); } @Override public E remove(int index) { tryLoadToIndex(index); return items.remove(index); } @Override public int indexOf(Object o) { int index = items.indexOf(o); if (index != -1) { return index; } while (hasNextPage()) { int itemsSize = items.size(); List<E> nextPageItems = pagedResponseIterator.next().getValue(); this.items.addAll(nextPageItems); index = nextPageItems.indexOf(o); if (index != -1) { index = itemsSize + index; return index; } } return -1; } @Override public int lastIndexOf(Object o) { loadAll(); return items.lastIndexOf(o); } @Override public ListIterator<E> listIterator() { return new ListItr(0); } @Override public ListIterator<E> listIterator(int index) { tryLoadToIndex(index); return new ListItr(index); } @Override public List<E> subList(int fromIndex, int toIndex) { while ((fromIndex >= items.size() || toIndex >= items.size()) && hasNextPage()) { loadNextPage(); } return items.subList(fromIndex, toIndex); } private void tryLoadToIndex(int index) { while (index >= items.size() && hasNextPage()) { loadNextPage(); } } /** * The implementation of {@link ListIterator} for PagedList. */ private class ListItr implements ListIterator<E> { /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIterator. * * @param index the position in the list to start. */ ListItr(int index) { this.nextIndex = index; } @Override public boolean hasNext() { return this.nextIndex != items.size() || hasNextPage(); } @Override public E next() { if (this.nextIndex >= items.size()) { if (!hasNextPage()) { throw new NoSuchElementException(); } else { loadNextPage(); } return next(); } else { try { E nextItem = items.get(this.nextIndex); this.lastRetIndex = this.nextIndex; this.nextIndex = this.nextIndex + 1; return nextItem; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void remove() { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public boolean hasPrevious() { return this.nextIndex != 0; } @Override public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw new NoSuchElementException(); } else if (i >= items.size()) { throw new ConcurrentModificationException(); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetIndex); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public int nextIndex() { return this.nextIndex; } @Override public int previousIndex() { return this.nextIndex - 1; } @Override public void set(E e) { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.set(this.lastRetIndex, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void add(E e) { try { items.add(this.nextIndex, e); this.nextIndex = this.nextIndex + 1; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } }
class PagedList<E> implements List<E> { /** The items retrieved. */ private final List<E> items; /** The paged response iterator for not retrieved items. */ private Iterator<PagedResponse<E>> pagedResponseIterator; /** * Creates an instance of PagedList. */ public PagedList() { items = new ArrayList<>(); pagedResponseIterator = Collections.emptyIterator(); } /** * Creates an instance of PagedList from a {@link PagedIterable}. * * @param pagedIterable the {@link PagedIterable} object. */ public PagedList(PagedIterable<E> pagedIterable) { items = new ArrayList<>(); Objects.requireNonNull(pagedIterable, "'pagedIterable' cannot be null."); this.pagedResponseIterator = pagedIterable.iterableByPage().iterator(); } /** * If there are more pages available. * * @return true if there are more pages to load. False otherwise. */ protected boolean hasNextPage() { return pagedResponseIterator.hasNext(); } /** * Loads a page from next page link. * The exceptions are wrapped into Java Runtime exceptions. */ /** * Keep loading the next page from the next page link until all items are loaded. */ public void loadAll() { while (hasNextPage()) { loadNextPage(); } } @Override public int size() { loadAll(); return items.size(); } @Override public boolean isEmpty() { return items.isEmpty() && !hasNextPage(); } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Iterator<E> iterator() { return new ListItr(0); } @Override public Object[] toArray() { loadAll(); return items.toArray(); } @Override public <T> T[] toArray(T[] a) { loadAll(); return items.toArray(a); } @Override public boolean add(E e) { loadAll(); return items.add(e); } @Override public boolean remove(Object o) { int index = indexOf(o); if (index != -1) { items.remove(index); return true; } else { return false; } } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) { if (!contains(e)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends E> c) { return items.addAll(c); } @Override public boolean addAll(int index, Collection<? extends E> c) { return items.addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return items.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return items.retainAll(c); } @Override public void clear() { items.clear(); pagedResponseIterator = Collections.emptyIterator(); } @Override public E get(int index) { tryLoadToIndex(index); return items.get(index); } @Override public E set(int index, E element) { tryLoadToIndex(index); return items.set(index, element); } @Override public void add(int index, E element) { items.add(index, element); } @Override public E remove(int index) { tryLoadToIndex(index); return items.remove(index); } @Override public int indexOf(Object o) { int index = items.indexOf(o); if (index != -1) { return index; } while (hasNextPage()) { int itemsSize = items.size(); List<E> nextPageItems = pagedResponseIterator.next().getValue(); this.items.addAll(nextPageItems); index = nextPageItems.indexOf(o); if (index != -1) { index = itemsSize + index; return index; } } return -1; } @Override public int lastIndexOf(Object o) { loadAll(); return items.lastIndexOf(o); } @Override public ListIterator<E> listIterator() { return new ListItr(0); } @Override public ListIterator<E> listIterator(int index) { tryLoadToIndex(index); return new ListItr(index); } @Override public List<E> subList(int fromIndex, int toIndex) { while ((fromIndex >= items.size() || toIndex >= items.size()) && hasNextPage()) { loadNextPage(); } return items.subList(fromIndex, toIndex); } private void tryLoadToIndex(int index) { while (index >= items.size() && hasNextPage()) { loadNextPage(); } } /** * The implementation of {@link ListIterator} for PagedList. */ private class ListItr implements ListIterator<E> { /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIterator. * * @param index the position in the list to start. */ ListItr(int index) { this.nextIndex = index; } @Override public boolean hasNext() { return this.nextIndex != items.size() || hasNextPage(); } @Override public E next() { if (this.nextIndex >= items.size()) { if (!hasNextPage()) { throw new NoSuchElementException(); } else { loadNextPage(); } return next(); } else { try { E nextItem = items.get(this.nextIndex); this.lastRetIndex = this.nextIndex; this.nextIndex = this.nextIndex + 1; return nextItem; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void remove() { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public boolean hasPrevious() { return this.nextIndex != 0; } @Override public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw new NoSuchElementException(); } else if (i >= items.size()) { throw new ConcurrentModificationException(); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetIndex); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public int nextIndex() { return this.nextIndex; } @Override public int previousIndex() { return this.nextIndex - 1; } @Override public void set(E e) { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.set(this.lastRetIndex, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void add(E e) { try { items.add(this.nextIndex, e); this.nextIndex = this.nextIndex + 1; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } }
I don't know if this is the correct operator, what if there are multiple instants? `.single()` would throw an exception if there were more than one element.
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); }
.last()
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
Is there a reason you're creating another array with the same content?
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
REQUEST_RESPONSE_RENEWLOCK_OPERATION -> REQUEST_RESPONSE_RENEW_LOCK_OPERATION
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION,
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
What if the status isn't OK? We should return an error.
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) {
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
You need to run Alt+Shift+L to reformat the code. There is incorrect spacing on a few lines.
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) {
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
All this logic can be moved to MessageSerializer.
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage);
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
thanks for clarification. Then in our sample or migration guide, pls use PagedIterable as right and long term way for paging operation.
protected void loadNextPage() { this.items.addAll(pagedResponseIterator.next().getValue()); }
this.items.addAll(pagedResponseIterator.next().getValue());
protected void loadNextPage() { this.items.addAll(pagedResponseIterator.next().getValue()); }
class PagedList<E> implements List<E> { /** The items retrieved. */ private final List<E> items; /** The paged response iterator for not retrieved items. */ private Iterator<PagedResponse<E>> pagedResponseIterator; /** * Creates an instance of PagedList. */ public PagedList() { items = new ArrayList<>(); pagedResponseIterator = Collections.emptyIterator(); } /** * Creates an instance of PagedList from a {@link PagedIterable}. * * @param pagedIterable the {@link PagedIterable} object. */ public PagedList(PagedIterable<E> pagedIterable) { items = new ArrayList<>(); Objects.requireNonNull(pagedIterable, "'pagedIterable' cannot be null."); this.pagedResponseIterator = pagedIterable.iterableByPage().iterator(); } /** * If there are more pages available. * * @return true if there are more pages to load. False otherwise. */ protected boolean hasNextPage() { return pagedResponseIterator.hasNext(); } /** * Loads a page from next page link. * The exceptions are wrapped into Java Runtime exceptions. */ /** * Keep loading the next page from the next page link until all items are loaded. */ public void loadAll() { while (hasNextPage()) { loadNextPage(); } } @Override public int size() { loadAll(); return items.size(); } @Override public boolean isEmpty() { return items.isEmpty() && !hasNextPage(); } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Iterator<E> iterator() { return new ListItr(0); } @Override public Object[] toArray() { loadAll(); return items.toArray(); } @Override public <T> T[] toArray(T[] a) { loadAll(); return items.toArray(a); } @Override public boolean add(E e) { loadAll(); return items.add(e); } @Override public boolean remove(Object o) { int index = indexOf(o); if (index != -1) { items.remove(index); return true; } else { return false; } } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) { if (!contains(e)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends E> c) { return items.addAll(c); } @Override public boolean addAll(int index, Collection<? extends E> c) { return items.addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return items.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return items.retainAll(c); } @Override public void clear() { items.clear(); pagedResponseIterator = Collections.emptyIterator(); } @Override public E get(int index) { tryLoadToIndex(index); return items.get(index); } @Override public E set(int index, E element) { tryLoadToIndex(index); return items.set(index, element); } @Override public void add(int index, E element) { items.add(index, element); } @Override public E remove(int index) { tryLoadToIndex(index); return items.remove(index); } @Override public int indexOf(Object o) { int index = items.indexOf(o); if (index != -1) { return index; } while (hasNextPage()) { int itemsSize = items.size(); List<E> nextPageItems = pagedResponseIterator.next().getValue(); this.items.addAll(nextPageItems); index = nextPageItems.indexOf(o); if (index != -1) { index = itemsSize + index; return index; } } return -1; } @Override public int lastIndexOf(Object o) { loadAll(); return items.lastIndexOf(o); } @Override public ListIterator<E> listIterator() { return new ListItr(0); } @Override public ListIterator<E> listIterator(int index) { tryLoadToIndex(index); return new ListItr(index); } @Override public List<E> subList(int fromIndex, int toIndex) { while ((fromIndex >= items.size() || toIndex >= items.size()) && hasNextPage()) { loadNextPage(); } return items.subList(fromIndex, toIndex); } private void tryLoadToIndex(int index) { while (index >= items.size() && hasNextPage()) { loadNextPage(); } } /** * The implementation of {@link ListIterator} for PagedList. */ private class ListItr implements ListIterator<E> { /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIterator. * * @param index the position in the list to start. */ ListItr(int index) { this.nextIndex = index; } @Override public boolean hasNext() { return this.nextIndex != items.size() || hasNextPage(); } @Override public E next() { if (this.nextIndex >= items.size()) { if (!hasNextPage()) { throw new NoSuchElementException(); } else { loadNextPage(); } return next(); } else { try { E nextItem = items.get(this.nextIndex); this.lastRetIndex = this.nextIndex; this.nextIndex = this.nextIndex + 1; return nextItem; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void remove() { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public boolean hasPrevious() { return this.nextIndex != 0; } @Override public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw new NoSuchElementException(); } else if (i >= items.size()) { throw new ConcurrentModificationException(); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetIndex); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public int nextIndex() { return this.nextIndex; } @Override public int previousIndex() { return this.nextIndex - 1; } @Override public void set(E e) { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.set(this.lastRetIndex, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void add(E e) { try { items.add(this.nextIndex, e); this.nextIndex = this.nextIndex + 1; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } }
class PagedList<E> implements List<E> { /** The items retrieved. */ private final List<E> items; /** The paged response iterator for not retrieved items. */ private Iterator<PagedResponse<E>> pagedResponseIterator; /** * Creates an instance of PagedList. */ public PagedList() { items = new ArrayList<>(); pagedResponseIterator = Collections.emptyIterator(); } /** * Creates an instance of PagedList from a {@link PagedIterable}. * * @param pagedIterable the {@link PagedIterable} object. */ public PagedList(PagedIterable<E> pagedIterable) { items = new ArrayList<>(); Objects.requireNonNull(pagedIterable, "'pagedIterable' cannot be null."); this.pagedResponseIterator = pagedIterable.iterableByPage().iterator(); } /** * If there are more pages available. * * @return true if there are more pages to load. False otherwise. */ protected boolean hasNextPage() { return pagedResponseIterator.hasNext(); } /** * Loads a page from next page link. * The exceptions are wrapped into Java Runtime exceptions. */ /** * Keep loading the next page from the next page link until all items are loaded. */ public void loadAll() { while (hasNextPage()) { loadNextPage(); } } @Override public int size() { loadAll(); return items.size(); } @Override public boolean isEmpty() { return items.isEmpty() && !hasNextPage(); } @Override public boolean contains(Object o) { return indexOf(o) >= 0; } @Override public Iterator<E> iterator() { return new ListItr(0); } @Override public Object[] toArray() { loadAll(); return items.toArray(); } @Override public <T> T[] toArray(T[] a) { loadAll(); return items.toArray(a); } @Override public boolean add(E e) { loadAll(); return items.add(e); } @Override public boolean remove(Object o) { int index = indexOf(o); if (index != -1) { items.remove(index); return true; } else { return false; } } @Override public boolean containsAll(Collection<?> c) { for (Object e : c) { if (!contains(e)) { return false; } } return true; } @Override public boolean addAll(Collection<? extends E> c) { return items.addAll(c); } @Override public boolean addAll(int index, Collection<? extends E> c) { return items.addAll(index, c); } @Override public boolean removeAll(Collection<?> c) { return items.removeAll(c); } @Override public boolean retainAll(Collection<?> c) { return items.retainAll(c); } @Override public void clear() { items.clear(); pagedResponseIterator = Collections.emptyIterator(); } @Override public E get(int index) { tryLoadToIndex(index); return items.get(index); } @Override public E set(int index, E element) { tryLoadToIndex(index); return items.set(index, element); } @Override public void add(int index, E element) { items.add(index, element); } @Override public E remove(int index) { tryLoadToIndex(index); return items.remove(index); } @Override public int indexOf(Object o) { int index = items.indexOf(o); if (index != -1) { return index; } while (hasNextPage()) { int itemsSize = items.size(); List<E> nextPageItems = pagedResponseIterator.next().getValue(); this.items.addAll(nextPageItems); index = nextPageItems.indexOf(o); if (index != -1) { index = itemsSize + index; return index; } } return -1; } @Override public int lastIndexOf(Object o) { loadAll(); return items.lastIndexOf(o); } @Override public ListIterator<E> listIterator() { return new ListItr(0); } @Override public ListIterator<E> listIterator(int index) { tryLoadToIndex(index); return new ListItr(index); } @Override public List<E> subList(int fromIndex, int toIndex) { while ((fromIndex >= items.size() || toIndex >= items.size()) && hasNextPage()) { loadNextPage(); } return items.subList(fromIndex, toIndex); } private void tryLoadToIndex(int index) { while (index >= items.size() && hasNextPage()) { loadNextPage(); } } /** * The implementation of {@link ListIterator} for PagedList. */ private class ListItr implements ListIterator<E> { /** * index of next element to return. */ private int nextIndex; /** * index of last element returned; -1 if no such action happened. */ private int lastRetIndex = -1; /** * Creates an instance of the ListIterator. * * @param index the position in the list to start. */ ListItr(int index) { this.nextIndex = index; } @Override public boolean hasNext() { return this.nextIndex != items.size() || hasNextPage(); } @Override public E next() { if (this.nextIndex >= items.size()) { if (!hasNextPage()) { throw new NoSuchElementException(); } else { loadNextPage(); } return next(); } else { try { E nextItem = items.get(this.nextIndex); this.lastRetIndex = this.nextIndex; this.nextIndex = this.nextIndex + 1; return nextItem; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void remove() { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.remove(this.lastRetIndex); this.nextIndex = this.lastRetIndex; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public boolean hasPrevious() { return this.nextIndex != 0; } @Override public E previous() { int i = this.nextIndex - 1; if (i < 0) { throw new NoSuchElementException(); } else if (i >= items.size()) { throw new ConcurrentModificationException(); } else { try { this.nextIndex = i; this.lastRetIndex = i; return items.get(this.lastRetIndex); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public int nextIndex() { return this.nextIndex; } @Override public int previousIndex() { return this.nextIndex - 1; } @Override public void set(E e) { if (this.lastRetIndex < 0) { throw new IllegalStateException(); } else { try { items.set(this.lastRetIndex, e); } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } @Override public void add(E e) { try { items.add(this.nextIndex, e); this.nextIndex = this.nextIndex + 1; this.lastRetIndex = -1; } catch (IndexOutOfBoundsException ex) { throw new ConcurrentModificationException(); } } } }
This unchecked cast makes me nervous. I would be more defensive about casting (ie. checking instanceof).
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
This variable creation isn't necessary if you're going to pass it immediately to the next line.
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
Date[] expirations = (Date[]) expirationListObj;
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
Instead of returning Flux.fromIterable, you could have kept it as a stream instead of collecting it twice and using fromStream
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
return Flux.fromIterable(expirationsForLocks);
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
removing it.
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
Normally service would return one because we are sending one lock token . But in track1 also , they are using same logic since AMQP message comes as array in case of one lock token.
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); }
.last()
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
moved to serializer.
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); }
int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage);
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
```suggestion if (expirationListObj instanceof Date[]) { ```
private List<Instant> deserializeListOfInstant(Message amqpMessage) { List<Instant> listInstant = new ArrayList<>(); if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { listInstant = Arrays.stream((Date[]) expirationListObj) .map(Date::toInstant) .collect(Collectors.toList()); } } } return listInstant; }
if (expirationListObj instanceof Date[]) {
private List<Instant> deserializeListOfInstant(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(Date::toInstant) .collect(Collectors.toList()); } } } return Collections.emptyList(); }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String ENQUEUED_TIME_UTC_NAME = "x-opt-enqueued-time"; private static final String SCHEDULED_ENQUEUE_TIME_NAME = "x-opt-scheduled-enqueue-time"; private static final String SEQUENCE_NUMBER_NAME = "x-opt-sequence-number"; private static final String LOCKED_UNTIL_NAME = "x-opt-locked-until"; private static final String PARTITION_KEY_NAME = "x-opt-partition-key"; private static final String VIA_PARTITION_KEY_NAME = "x-opt-via-partition-key"; private static final String DEAD_LETTER_SOURCE_NAME = "x-opt-deadletter-source"; private static final String REQUEST_RESPONSE_MESSAGES = "messages"; private static final String REQUEST_RESPONSE_MESSAGE = "message"; private static final String REQUEST_RESPONSE_EXPIRATIONS = "expirations"; private final ClientLogger logger = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; final Message amqpMessage = Proton.message(); final byte[] body = brokeredMessage.getBody(); amqpMessage.setBody(new Data(new Binary(body))); if (brokeredMessage.getProperties() != null) { amqpMessage.setApplicationProperties(new ApplicationProperties(brokeredMessage.getProperties())); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getLabel()); amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_TIME_NAME), Date.from(brokeredMessage.getScheduledEnqueueTime())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_NAME), brokeredMessage.getPartitionKey()); } final String viaPartitionKey = brokeredMessage.getViaPartitionKey(); if (viaPartitionKey != null && !viaPartitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(VIA_PARTITION_KEY_NAME), viaPartitionKey); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); return amqpMessage; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == Instant.class) { return (List<T>) deserializeListOfInstant(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final int statusCode = RequestResponseUtils.getResponseStatusCode(amqpMessage); if (AmqpResponseCode.fromValue(statusCode) != AmqpResponseCode.OK) { logger.warning("AMQP response did not contain OK status code. Actual: {}", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { logger.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { logger.warning("AMQP response body is not correct instance. Expected: {}. Actual: {}", Map.class, responseBodyMap.getClass()); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(REQUEST_RESPONSE_MESSAGES); if (messages == null) { logger.warning("Response body did not contain key: {}", REQUEST_RESPONSE_MESSAGES); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { logger.warning("Response body contents is not the correct type. Expected: {}. Actual: {}", Iterable.class, messages.getClass()); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { logger.warning("Message inside iterable of message is not correct type. Expected: {}. Actual: {}", Map.class, message.getClass()); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(REQUEST_RESPONSE_MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); messageList.add(receivedMessage); } return messageList; } private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final ServiceBusReceivedMessage brokeredMessage; final Section body = amqpMessage.getBody(); if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); final byte[] bytes = messageData.getArray(); brokeredMessage = new ServiceBusReceivedMessage(bytes); } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, body.getType())); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, "null")); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { brokeredMessage.getProperties().putAll(applicationProperties.getValue()); } brokeredMessage.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredMessage.setDeliveryCount(amqpMessage.getDeliveryCount()); final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredMessage.setMessageId(messageId.toString()); } brokeredMessage.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredMessage.setCorrelationId(correlationId.toString()); } final Properties properties = amqpMessage.getProperties(); if (properties != null) { brokeredMessage.setTo(properties.getTo()); } brokeredMessage.setLabel(amqpMessage.getSubject()); brokeredMessage.setReplyTo(amqpMessage.getReplyTo()); brokeredMessage.setReplyToSessionId(amqpMessage.getReplyToGroupId()); brokeredMessage.setSessionId(amqpMessage.getGroupId()); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { Map<Symbol, Object> messageAnnotationsMap = messageAnnotations.getValue(); if (messageAnnotationsMap != null) { for (Map.Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); switch (key) { case ENQUEUED_TIME_UTC_NAME: brokeredMessage.setEnqueuedTime(((Date) value).toInstant()); break; case SCHEDULED_ENQUEUE_TIME_NAME: brokeredMessage.setScheduledEnqueueTime(((Date) value).toInstant()); break; case SEQUENCE_NUMBER_NAME: brokeredMessage.setSequenceNumber((long) value); break; case LOCKED_UNTIL_NAME: brokeredMessage.setLockedUntil(((Date) value).toInstant()); break; case PARTITION_KEY_NAME: brokeredMessage.setPartitionKey((String) value); break; case VIA_PARTITION_KEY_NAME: brokeredMessage.setViaPartitionKey((String) value); break; case DEAD_LETTER_SOURCE_NAME: brokeredMessage.setDeadLetterSource((String) value); break; default: logger.info("Unrecognised key: {}, value: {}", key, value); break; } } } } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String ENQUEUED_TIME_UTC_NAME = "x-opt-enqueued-time"; private static final String SCHEDULED_ENQUEUE_TIME_NAME = "x-opt-scheduled-enqueue-time"; private static final String SEQUENCE_NUMBER_NAME = "x-opt-sequence-number"; private static final String LOCKED_UNTIL_NAME = "x-opt-locked-until"; private static final String PARTITION_KEY_NAME = "x-opt-partition-key"; private static final String VIA_PARTITION_KEY_NAME = "x-opt-via-partition-key"; private static final String DEAD_LETTER_SOURCE_NAME = "x-opt-deadletter-source"; private static final String REQUEST_RESPONSE_MESSAGES = "messages"; private static final String REQUEST_RESPONSE_MESSAGE = "message"; private static final String REQUEST_RESPONSE_EXPIRATIONS = "expirations"; private final ClientLogger logger = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; final Message amqpMessage = Proton.message(); final byte[] body = brokeredMessage.getBody(); amqpMessage.setBody(new Data(new Binary(body))); if (brokeredMessage.getProperties() != null) { amqpMessage.setApplicationProperties(new ApplicationProperties(brokeredMessage.getProperties())); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getLabel()); amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_TIME_NAME), Date.from(brokeredMessage.getScheduledEnqueueTime())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_NAME), brokeredMessage.getPartitionKey()); } final String viaPartitionKey = brokeredMessage.getViaPartitionKey(); if (viaPartitionKey != null && !viaPartitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(VIA_PARTITION_KEY_NAME), viaPartitionKey); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); return amqpMessage; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == Instant.class) { return (List<T>) deserializeListOfInstant(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final int statusCode = RequestResponseUtils.getResponseStatusCode(amqpMessage); if (AmqpResponseCode.fromValue(statusCode) != AmqpResponseCode.OK) { logger.warning("AMQP response did not contain OK status code. Actual: {}", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { logger.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { logger.warning("AMQP response body is not correct instance. Expected: {}. Actual: {}", Map.class, responseBodyMap.getClass()); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(REQUEST_RESPONSE_MESSAGES); if (messages == null) { logger.warning("Response body did not contain key: {}", REQUEST_RESPONSE_MESSAGES); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { logger.warning("Response body contents is not the correct type. Expected: {}. Actual: {}", Iterable.class, messages.getClass()); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { logger.warning("Message inside iterable of message is not correct type. Expected: {}. Actual: {}", Map.class, message.getClass()); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(REQUEST_RESPONSE_MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); messageList.add(receivedMessage); } return messageList; } private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final ServiceBusReceivedMessage brokeredMessage; final Section body = amqpMessage.getBody(); if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); final byte[] bytes = messageData.getArray(); brokeredMessage = new ServiceBusReceivedMessage(bytes); } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, body.getType())); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, "null")); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { brokeredMessage.getProperties().putAll(applicationProperties.getValue()); } brokeredMessage.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredMessage.setDeliveryCount(amqpMessage.getDeliveryCount()); final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredMessage.setMessageId(messageId.toString()); } brokeredMessage.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredMessage.setCorrelationId(correlationId.toString()); } final Properties properties = amqpMessage.getProperties(); if (properties != null) { brokeredMessage.setTo(properties.getTo()); } brokeredMessage.setLabel(amqpMessage.getSubject()); brokeredMessage.setReplyTo(amqpMessage.getReplyTo()); brokeredMessage.setReplyToSessionId(amqpMessage.getReplyToGroupId()); brokeredMessage.setSessionId(amqpMessage.getGroupId()); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { Map<Symbol, Object> messageAnnotationsMap = messageAnnotations.getValue(); if (messageAnnotationsMap != null) { for (Map.Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); switch (key) { case ENQUEUED_TIME_UTC_NAME: brokeredMessage.setEnqueuedTime(((Date) value).toInstant()); break; case SCHEDULED_ENQUEUE_TIME_NAME: brokeredMessage.setScheduledEnqueueTime(((Date) value).toInstant()); break; case SEQUENCE_NUMBER_NAME: brokeredMessage.setSequenceNumber((long) value); break; case LOCKED_UNTIL_NAME: brokeredMessage.setLockedUntil(((Date) value).toInstant()); break; case PARTITION_KEY_NAME: brokeredMessage.setPartitionKey((String) value); break; case VIA_PARTITION_KEY_NAME: brokeredMessage.setViaPartitionKey((String) value); break; case DEAD_LETTER_SOURCE_NAME: brokeredMessage.setDeadLetterSource((String) value); break; default: logger.info("Unrecognised key: {}, value: {}", key, value); break; } } } } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
You don't need this variable because you reassign it later anyways. Return a collections.emptylist in the other cases.
private List<Instant> deserializeListOfInstant(Message amqpMessage) { List<Instant> listInstant = new ArrayList<>(); if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { listInstant = Arrays.stream((Date[]) expirationListObj) .map(Date::toInstant) .collect(Collectors.toList()); } } } return listInstant; }
List<Instant> listInstant = new ArrayList<>();
private List<Instant> deserializeListOfInstant(Message amqpMessage) { if (amqpMessage.getBody() instanceof AmqpValue) { AmqpValue amqpValue = ((AmqpValue) amqpMessage.getBody()); if (amqpValue.getValue() instanceof Map) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) amqpValue.getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { return Arrays.stream((Date[]) expirationListObj) .map(Date::toInstant) .collect(Collectors.toList()); } } } return Collections.emptyList(); }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String ENQUEUED_TIME_UTC_NAME = "x-opt-enqueued-time"; private static final String SCHEDULED_ENQUEUE_TIME_NAME = "x-opt-scheduled-enqueue-time"; private static final String SEQUENCE_NUMBER_NAME = "x-opt-sequence-number"; private static final String LOCKED_UNTIL_NAME = "x-opt-locked-until"; private static final String PARTITION_KEY_NAME = "x-opt-partition-key"; private static final String VIA_PARTITION_KEY_NAME = "x-opt-via-partition-key"; private static final String DEAD_LETTER_SOURCE_NAME = "x-opt-deadletter-source"; private static final String REQUEST_RESPONSE_MESSAGES = "messages"; private static final String REQUEST_RESPONSE_MESSAGE = "message"; private static final String REQUEST_RESPONSE_EXPIRATIONS = "expirations"; private final ClientLogger logger = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; final Message amqpMessage = Proton.message(); final byte[] body = brokeredMessage.getBody(); amqpMessage.setBody(new Data(new Binary(body))); if (brokeredMessage.getProperties() != null) { amqpMessage.setApplicationProperties(new ApplicationProperties(brokeredMessage.getProperties())); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getLabel()); amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_TIME_NAME), Date.from(brokeredMessage.getScheduledEnqueueTime())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_NAME), brokeredMessage.getPartitionKey()); } final String viaPartitionKey = brokeredMessage.getViaPartitionKey(); if (viaPartitionKey != null && !viaPartitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(VIA_PARTITION_KEY_NAME), viaPartitionKey); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); return amqpMessage; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == Instant.class) { return (List<T>) deserializeListOfInstant(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final int statusCode = RequestResponseUtils.getResponseStatusCode(amqpMessage); if (AmqpResponseCode.fromValue(statusCode) != AmqpResponseCode.OK) { logger.warning("AMQP response did not contain OK status code. Actual: {}", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { logger.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { logger.warning("AMQP response body is not correct instance. Expected: {}. Actual: {}", Map.class, responseBodyMap.getClass()); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(REQUEST_RESPONSE_MESSAGES); if (messages == null) { logger.warning("Response body did not contain key: {}", REQUEST_RESPONSE_MESSAGES); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { logger.warning("Response body contents is not the correct type. Expected: {}. Actual: {}", Iterable.class, messages.getClass()); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { logger.warning("Message inside iterable of message is not correct type. Expected: {}. Actual: {}", Map.class, message.getClass()); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(REQUEST_RESPONSE_MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); messageList.add(receivedMessage); } return messageList; } private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final ServiceBusReceivedMessage brokeredMessage; final Section body = amqpMessage.getBody(); if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); final byte[] bytes = messageData.getArray(); brokeredMessage = new ServiceBusReceivedMessage(bytes); } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, body.getType())); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, "null")); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { brokeredMessage.getProperties().putAll(applicationProperties.getValue()); } brokeredMessage.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredMessage.setDeliveryCount(amqpMessage.getDeliveryCount()); final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredMessage.setMessageId(messageId.toString()); } brokeredMessage.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredMessage.setCorrelationId(correlationId.toString()); } final Properties properties = amqpMessage.getProperties(); if (properties != null) { brokeredMessage.setTo(properties.getTo()); } brokeredMessage.setLabel(amqpMessage.getSubject()); brokeredMessage.setReplyTo(amqpMessage.getReplyTo()); brokeredMessage.setReplyToSessionId(amqpMessage.getReplyToGroupId()); brokeredMessage.setSessionId(amqpMessage.getGroupId()); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { Map<Symbol, Object> messageAnnotationsMap = messageAnnotations.getValue(); if (messageAnnotationsMap != null) { for (Map.Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); switch (key) { case ENQUEUED_TIME_UTC_NAME: brokeredMessage.setEnqueuedTime(((Date) value).toInstant()); break; case SCHEDULED_ENQUEUE_TIME_NAME: brokeredMessage.setScheduledEnqueueTime(((Date) value).toInstant()); break; case SEQUENCE_NUMBER_NAME: brokeredMessage.setSequenceNumber((long) value); break; case LOCKED_UNTIL_NAME: brokeredMessage.setLockedUntil(((Date) value).toInstant()); break; case PARTITION_KEY_NAME: brokeredMessage.setPartitionKey((String) value); break; case VIA_PARTITION_KEY_NAME: brokeredMessage.setViaPartitionKey((String) value); break; case DEAD_LETTER_SOURCE_NAME: brokeredMessage.setDeadLetterSource((String) value); break; default: logger.info("Unrecognised key: {}, value: {}", key, value); break; } } } } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
class ServiceBusMessageSerializer implements MessageSerializer { private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; private static final String ENQUEUED_TIME_UTC_NAME = "x-opt-enqueued-time"; private static final String SCHEDULED_ENQUEUE_TIME_NAME = "x-opt-scheduled-enqueue-time"; private static final String SEQUENCE_NUMBER_NAME = "x-opt-sequence-number"; private static final String LOCKED_UNTIL_NAME = "x-opt-locked-until"; private static final String PARTITION_KEY_NAME = "x-opt-partition-key"; private static final String VIA_PARTITION_KEY_NAME = "x-opt-via-partition-key"; private static final String DEAD_LETTER_SOURCE_NAME = "x-opt-deadletter-source"; private static final String REQUEST_RESPONSE_MESSAGES = "messages"; private static final String REQUEST_RESPONSE_MESSAGE = "message"; private static final String REQUEST_RESPONSE_EXPIRATIONS = "expirations"; private final ClientLogger logger = new ClientLogger(ServiceBusMessageSerializer.class); /** * Gets the serialized size of the AMQP message. */ @Override public int getSize(Message amqpMessage) { if (amqpMessage == null) { return 0; } int payloadSize = getPayloadSize(amqpMessage); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); final ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); int annotationsSize = 0; int applicationPropertiesSize = 0; if (messageAnnotations != null) { final Map<Symbol, Object> map = messageAnnotations.getValue(); for (Map.Entry<Symbol, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); annotationsSize += size; } } if (applicationProperties != null) { final Map<String, Object> map = applicationProperties.getValue(); for (Map.Entry<String, Object> entry : map.entrySet()) { final int size = sizeof(entry.getKey()) + sizeof(entry.getValue()); applicationPropertiesSize += size; } } return annotationsSize + applicationPropertiesSize + payloadSize; } /** * Creates the AMQP message represented by this {@code object}. Currently, only supports serializing {@link * ServiceBusMessage}. * * @param object Concrete object to deserialize. * * @return A new AMQP message for this {@code object}. * * @throws IllegalArgumentException if {@code object} is not an instance of {@link ServiceBusMessage}. */ @Override public <T> Message serialize(T object) { Objects.requireNonNull(object, "'object' to serialize cannot be null."); if (!(object instanceof ServiceBusMessage)) { throw logger.logExceptionAsError(new IllegalArgumentException( "Cannot serialize object that is not ServiceBusMessage. Clazz: " + object.getClass())); } final ServiceBusMessage brokeredMessage = (ServiceBusMessage) object; final Message amqpMessage = Proton.message(); final byte[] body = brokeredMessage.getBody(); amqpMessage.setBody(new Data(new Binary(body))); if (brokeredMessage.getProperties() != null) { amqpMessage.setApplicationProperties(new ApplicationProperties(brokeredMessage.getProperties())); } if (brokeredMessage.getTimeToLive() != null) { amqpMessage.setTtl(brokeredMessage.getTimeToLive().toMillis()); } if (amqpMessage.getProperties() == null) { amqpMessage.setProperties(new Properties()); } amqpMessage.setMessageId(brokeredMessage.getMessageId()); amqpMessage.setContentType(brokeredMessage.getContentType()); amqpMessage.setCorrelationId(brokeredMessage.getCorrelationId()); amqpMessage.setSubject(brokeredMessage.getLabel()); amqpMessage.getProperties().setTo(brokeredMessage.getTo()); amqpMessage.setReplyTo(brokeredMessage.getReplyTo()); amqpMessage.setReplyToGroupId(brokeredMessage.getReplyToSessionId()); amqpMessage.setGroupId(brokeredMessage.getSessionId()); final Map<Symbol, Object> messageAnnotationsMap = new HashMap<>(); if (brokeredMessage.getScheduledEnqueueTime() != null) { messageAnnotationsMap.put(Symbol.valueOf(SCHEDULED_ENQUEUE_TIME_NAME), Date.from(brokeredMessage.getScheduledEnqueueTime())); } final String partitionKey = brokeredMessage.getPartitionKey(); if (partitionKey != null && !partitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(PARTITION_KEY_NAME), brokeredMessage.getPartitionKey()); } final String viaPartitionKey = brokeredMessage.getViaPartitionKey(); if (viaPartitionKey != null && !viaPartitionKey.isEmpty()) { messageAnnotationsMap.put(Symbol.valueOf(VIA_PARTITION_KEY_NAME), viaPartitionKey); } amqpMessage.setMessageAnnotations(new MessageAnnotations(messageAnnotationsMap)); return amqpMessage; } @SuppressWarnings("unchecked") @Override public <T> T deserialize(Message message, Class<T> clazz) { Objects.requireNonNull(message, "'message' cannot be null."); Objects.requireNonNull(clazz, "'clazz' cannot be null."); if (clazz == ServiceBusReceivedMessage.class) { return (T) deserializeMessage(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } @SuppressWarnings("unchecked") @Override public <T> List<T> deserializeList(Message message, Class<T> clazz) { if (clazz == ServiceBusReceivedMessage.class) { return (List<T>) deserializeListOfMessages(message); } else if (clazz == Instant.class) { return (List<T>) deserializeListOfInstant(message); } else { throw logger.logExceptionAsError(new IllegalArgumentException( "Deserialization only supports ServiceBusReceivedMessage.")); } } private List<ServiceBusReceivedMessage> deserializeListOfMessages(Message amqpMessage) { final List<ServiceBusReceivedMessage> messageList = new ArrayList<>(); final int statusCode = RequestResponseUtils.getResponseStatusCode(amqpMessage); if (AmqpResponseCode.fromValue(statusCode) != AmqpResponseCode.OK) { logger.warning("AMQP response did not contain OK status code. Actual: {}", statusCode); return Collections.emptyList(); } final Object responseBodyMap = ((AmqpValue) amqpMessage.getBody()).getValue(); if (responseBodyMap == null) { logger.warning("AMQP response did not contain a body."); return Collections.emptyList(); } else if (!(responseBodyMap instanceof Map)) { logger.warning("AMQP response body is not correct instance. Expected: {}. Actual: {}", Map.class, responseBodyMap.getClass()); return Collections.emptyList(); } final Object messages = ((Map) responseBodyMap).get(REQUEST_RESPONSE_MESSAGES); if (messages == null) { logger.warning("Response body did not contain key: {}", REQUEST_RESPONSE_MESSAGES); return Collections.emptyList(); } else if (!(messages instanceof Iterable)) { logger.warning("Response body contents is not the correct type. Expected: {}. Actual: {}", Iterable.class, messages.getClass()); return Collections.emptyList(); } for (Object message : (Iterable) messages) { if (!(message instanceof Map)) { logger.warning("Message inside iterable of message is not correct type. Expected: {}. Actual: {}", Map.class, message.getClass()); continue; } final Message responseMessage = Message.Factory.create(); final Binary messagePayLoad = (Binary) ((Map) message).get(REQUEST_RESPONSE_MESSAGE); responseMessage.decode(messagePayLoad.getArray(), messagePayLoad.getArrayOffset(), messagePayLoad.getLength()); final ServiceBusReceivedMessage receivedMessage = deserializeMessage(responseMessage); messageList.add(receivedMessage); } return messageList; } private ServiceBusReceivedMessage deserializeMessage(Message amqpMessage) { final ServiceBusReceivedMessage brokeredMessage; final Section body = amqpMessage.getBody(); if (body != null) { if (body instanceof Data) { final Binary messageData = ((Data) body).getValue(); final byte[] bytes = messageData.getArray(); brokeredMessage = new ServiceBusReceivedMessage(bytes); } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, body.getType())); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } } else { logger.warning(String.format(Messages.MESSAGE_NOT_OF_TYPE, "null")); brokeredMessage = new ServiceBusReceivedMessage(EMPTY_BYTE_ARRAY); } ApplicationProperties applicationProperties = amqpMessage.getApplicationProperties(); if (applicationProperties != null) { brokeredMessage.getProperties().putAll(applicationProperties.getValue()); } brokeredMessage.setTimeToLive(Duration.ofMillis(amqpMessage.getTtl())); brokeredMessage.setDeliveryCount(amqpMessage.getDeliveryCount()); final Object messageId = amqpMessage.getMessageId(); if (messageId != null) { brokeredMessage.setMessageId(messageId.toString()); } brokeredMessage.setContentType(amqpMessage.getContentType()); final Object correlationId = amqpMessage.getCorrelationId(); if (correlationId != null) { brokeredMessage.setCorrelationId(correlationId.toString()); } final Properties properties = amqpMessage.getProperties(); if (properties != null) { brokeredMessage.setTo(properties.getTo()); } brokeredMessage.setLabel(amqpMessage.getSubject()); brokeredMessage.setReplyTo(amqpMessage.getReplyTo()); brokeredMessage.setReplyToSessionId(amqpMessage.getReplyToGroupId()); brokeredMessage.setSessionId(amqpMessage.getGroupId()); final MessageAnnotations messageAnnotations = amqpMessage.getMessageAnnotations(); if (messageAnnotations != null) { Map<Symbol, Object> messageAnnotationsMap = messageAnnotations.getValue(); if (messageAnnotationsMap != null) { for (Map.Entry<Symbol, Object> entry : messageAnnotationsMap.entrySet()) { final String key = entry.getKey().toString(); final Object value = entry.getValue(); switch (key) { case ENQUEUED_TIME_UTC_NAME: brokeredMessage.setEnqueuedTime(((Date) value).toInstant()); break; case SCHEDULED_ENQUEUE_TIME_NAME: brokeredMessage.setScheduledEnqueueTime(((Date) value).toInstant()); break; case SEQUENCE_NUMBER_NAME: brokeredMessage.setSequenceNumber((long) value); break; case LOCKED_UNTIL_NAME: brokeredMessage.setLockedUntil(((Date) value).toInstant()); break; case PARTITION_KEY_NAME: brokeredMessage.setPartitionKey((String) value); break; case VIA_PARTITION_KEY_NAME: brokeredMessage.setViaPartitionKey((String) value); break; case DEAD_LETTER_SOURCE_NAME: brokeredMessage.setDeadLetterSource((String) value); break; default: logger.info("Unrecognised key: {}, value: {}", key, value); break; } } } } if (amqpMessage instanceof MessageWithLockToken) { brokeredMessage.setLockToken(((MessageWithLockToken) amqpMessage).getLockToken()); } return brokeredMessage; } private static int getPayloadSize(Message msg) { if (msg == null || msg.getBody() == null) { return 0; } final Section bodySection = msg.getBody(); if (bodySection instanceof AmqpValue) { return sizeof(((AmqpValue) bodySection).getValue()); } else if (bodySection instanceof AmqpSequence) { return sizeof(((AmqpSequence) bodySection).getValue()); } else if (bodySection instanceof Data) { final Data payloadSection = (Data) bodySection; final Binary payloadBytes = payloadSection.getValue(); return sizeof(payloadBytes); } else { return 0; } } @SuppressWarnings("rawtypes") private static int sizeof(Object obj) { if (obj == null) { return 0; } if (obj instanceof String) { return obj.toString().length() << 1; } if (obj instanceof Symbol) { return ((Symbol) obj).length() << 1; } if (obj instanceof Byte || obj instanceof UnsignedByte) { return Byte.BYTES; } if (obj instanceof Integer || obj instanceof UnsignedInteger) { return Integer.BYTES; } if (obj instanceof Long || obj instanceof UnsignedLong || obj instanceof Date) { return Long.BYTES; } if (obj instanceof Short || obj instanceof UnsignedShort) { return Short.BYTES; } if (obj instanceof Boolean) { return 1; } if (obj instanceof Character) { return 4; } if (obj instanceof Float) { return Float.BYTES; } if (obj instanceof Double) { return Double.BYTES; } if (obj instanceof UUID) { return 16; } if (obj instanceof Decimal32) { return 4; } if (obj instanceof Decimal64) { return 8; } if (obj instanceof Decimal128) { return 16; } if (obj instanceof Binary) { return ((Binary) obj).getLength(); } if (obj instanceof Declare) { return 7; } if (obj instanceof Discharge) { Discharge discharge = (Discharge) obj; return 12 + discharge.getTxnId().getLength(); } if (obj instanceof Map) { int size = 8; Map map = (Map) obj; for (Object value : map.keySet()) { size += sizeof(value); } for (Object value : map.values()) { size += sizeof(value); } return size; } if (obj instanceof Iterable) { int size = 8; for (Object innerObject : (Iterable) obj) { size += sizeof(innerObject); } return size; } if (obj.getClass().isArray()) { int size = 8; int length = Array.getLength(obj); for (int i = 0; i < length; i++) { size += sizeof(Array.get(obj, i)); } return size; } throw new IllegalArgumentException(String.format(Locale.US, "Encoding Type: %s is not supported", obj.getClass())); } }
Yes, and using .single() would force it to throw if there was more than one element in the flux. why not use `.next()` rather than `.last()` then? If the stream had 10000 elements, this would not complete until 9999 elements had been emitted.
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); }
.last()
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
Empty message? RE: ""
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext()));
private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
This is never disposed of in `@After`
protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); }
receiverManual = createBuilder()
protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat(() -> true) .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(Assertions::assertNotNull) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); } }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override @Override protected void afterTest() { dispose(receiver, receiverManual, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat() .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(receivedMessage -> { Assertions.assertNotNull(receivedMessage.getLockedUntil()); }) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); } }
Like I said, according to the spec this will never be null.
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat(() -> true) .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(Assertions::assertNotNull) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
.assertNext(Assertions::assertNotNull)
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat() .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(receivedMessage -> { Assertions.assertNotNull(receivedMessage.getLockedUntil()); }) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, receiverManual, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
I know you added comments and it doesn't make it reactive nor does it use StepVerifier correctly. * You've only hooked up the `doOnNext`, which is used for side effects like logging, but you use it for validation. the first overload of `subscribe` is a better fit. * What if the renewal fails? There is no handling of any error cases to fail the test * What if the operation never emits a value because it was hung? You don't handle that case either. Since we are pressed for time, can you create an issue to write tests for this?
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat(() -> true) .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(Assertions::assertNotNull) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken())
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat() .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(receivedMessage -> { Assertions.assertNotNull(receivedMessage.getLockedUntil()); }) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, receiverManual, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
You could have used. repeat() here.
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat(() -> true) .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(Assertions::assertNotNull) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
.repeat(() -> true)
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat() .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(receivedMessage -> { Assertions.assertNotNull(receivedMessage.getLockedUntil()); }) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, receiverManual, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
that should be fine I guess.
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .last() .publishOn(scheduler); }
.last()
public Mono<Instant> renewMessageLock(UUID lockToken) { return renewMessageLock(new UUID[]{lockToken}) .next() .publishOn(scheduler); }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override public Mono<Instant> renewMessageLock(ServiceBusReceivedMessage messageForLockRenew) { return renewMessageLock(new UUID[]{messageForLockRenew.getLockToken()}) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(REQUEST_RESPONSE_MESSAGE_COUNT, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { UUID[] lockTokens = Arrays.stream(renewLockList) .toArray(UUID[]::new); Message requestMessage = createManagementMessage(REQUEST_RESPONSE_RENEWLOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(REQUEST_RESPONSE_LOCKTOKENS, lockTokens))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); List<Instant> expirationsForLocks = new ArrayList<>(); if (statusCode == REQUEST_RESPONSE_OK_STATUS_CODE) { @SuppressWarnings("unchecked") Map<String, Object> responseBody = (Map<String, Object>) ((AmqpValue) responseMessage .getBody()).getValue(); Object expirationListObj = responseBody.get(REQUEST_RESPONSE_EXPIRATIONS); if (expirationListObj instanceof Date[]) { Date[] expirations = (Date[]) expirationListObj; expirationsForLocks = Arrays.stream(expirations) .map(Date::toInstant) .collect(Collectors.toList()); } } return Flux.fromIterable(expirationsForLocks); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
class ManagementChannel implements ServiceBusManagementNode { private final Scheduler scheduler; private final MessageSerializer messageSerializer; private final TokenManager tokenManager; private final Duration operationTimeout; private final Mono<RequestResponseChannel> createRequestResponse; private final String fullyQualifiedNamespace; private final ClientLogger logger; private final String entityPath; private final AtomicLong lastPeekedSequenceNumber = new AtomicLong(); private volatile boolean isDisposed; ManagementChannel(Mono<RequestResponseChannel> createRequestResponse, String fullyQualifiedNamespace, String entityPath, TokenManager tokenManager, MessageSerializer messageSerializer, Scheduler scheduler, Duration operationTimeout) { this.createRequestResponse = createRequestResponse; this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.logger = new ClientLogger(String.format("%s<%s>", ManagementChannel.class, entityPath)); this.entityPath = Objects.requireNonNull(entityPath, "'entityPath' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.scheduler = Objects.requireNonNull(scheduler, "'scheduler' cannot be null."); this.tokenManager = Objects.requireNonNull(tokenManager, "'tokenManager' cannot be null."); this.operationTimeout = operationTimeout; } @Override public Mono<Void> updateDisposition(UUID lockToken, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify) { return isAuthorized(UPDATE_DISPOSITION_OPERATION).then(createRequestResponse.flatMap(channel -> { final Message message = createDispositionMessage(new UUID[] {lockToken}, dispositionStatus, null, null, null, channel.getReceiveLinkName()); return channel.sendWithAck(message); }).flatMap(response -> { final int statusCode = RequestResponseUtils.getResponseStatusCode(response); final AmqpResponseCode responseCode = AmqpResponseCode.fromValue(statusCode); if (responseCode == AmqpResponseCode.OK) { return Mono.empty(); } else { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "", getErrorContext())); } })); } /** * {@inheritDoc} */ @Override /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek(long fromSequenceNumber) { return peek(fromSequenceNumber, 1, null) .last() .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages) { return peek(this.lastPeekedSequenceNumber.get() + 1, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Flux<ServiceBusReceivedMessage> peekBatch(int maxMessages, long fromSequenceNumber) { return peek(fromSequenceNumber, maxMessages, null) .publishOn(scheduler); } /** * {@inheritDoc} */ @Override public Mono<ServiceBusReceivedMessage> peek() { return peek(lastPeekedSequenceNumber.get() + 1); } private Flux<ServiceBusReceivedMessage> peek(long fromSequenceNumber, int maxMessages, UUID sessionId) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { final Message message = createManagementMessage(PEEK_OPERATION_VALUE, channel.getReceiveLinkName()); HashMap<String, Object> requestBodyMap = new HashMap<>(); requestBodyMap.put(REQUEST_RESPONSE_FROM_SEQUENCE_NUMBER, fromSequenceNumber); requestBodyMap.put(MESSAGE_COUNT_KEY, maxMessages); if (!Objects.isNull(sessionId)) { requestBodyMap.put(ManagementConstants.REQUEST_RESPONSE_SESSION_ID, sessionId); } message.setBody(new AmqpValue(requestBodyMap)); return channel.sendWithAck(message); }).flatMapMany(amqpMessage -> { final List<ServiceBusReceivedMessage> messageList = messageSerializer.deserializeList(amqpMessage, ServiceBusReceivedMessage.class); if (messageList.size() > 0) { final ServiceBusReceivedMessage receivedMessage = messageList.get(messageList.size() - 1); logger.info("Setting last peeked sequence number: {}", receivedMessage.getSequenceNumber()); if (receivedMessage.getSequenceNumber() > 0) { this.lastPeekedSequenceNumber.set(receivedMessage.getSequenceNumber()); } } return Flux.fromIterable(messageList); })); } private Mono<Void> isAuthorized(String operation) { return tokenManager.getAuthorizationResults().next().flatMap(response -> { if (response != AmqpResponseCode.ACCEPTED) { return Mono.error(new AmqpException(false, String.format( "User does not have authorization to perform operation [%s] on entity [%s]", operation, entityPath), getErrorContext())); } else { return Mono.empty(); } }); } private Message createDispositionMessage(UUID[] lockTokens, DispositionStatus dispositionStatus, String deadLetterReason, String deadLetterErrorDescription, Map<String, Object> propertiesToModify, String linkName) { logger.verbose("Update disposition of deliveries '{}' to '{}' on entity '{}', session '{}'", Arrays.toString(lockTokens), dispositionStatus, entityPath, "n/a"); final Message message = createManagementMessage(UPDATE_DISPOSITION_OPERATION, linkName); final Map<String, Object> requestBody = new HashMap<>(); requestBody.put(ManagementConstants.LOCK_TOKENS_KEY, lockTokens); requestBody.put(ManagementConstants.DISPOSITION_STATUS_KEY, dispositionStatus.getValue()); if (deadLetterReason != null) { requestBody.put(ManagementConstants.DEADLETTER_REASON_KEY, deadLetterReason); } if (deadLetterErrorDescription != null) { requestBody.put(ManagementConstants.DEADLETTER_DESCRIPTION_KEY, deadLetterErrorDescription); } if (propertiesToModify != null && propertiesToModify.size() > 0) { requestBody.put(ManagementConstants.PROPERTIES_TO_MODIFY_KEY, propertiesToModify); } message.setBody(new AmqpValue(requestBody)); return message; } private Flux<Instant> renewMessageLock(UUID[] renewLockList) { return isAuthorized(PEEK_OPERATION_VALUE).thenMany(createRequestResponse.flatMap(channel -> { Message requestMessage = createManagementMessage(RENEW_LOCK_OPERATION, channel.getReceiveLinkName()); requestMessage.setBody(new AmqpValue(Collections.singletonMap(LOCK_TOKENS, renewLockList))); return channel.sendWithAck(requestMessage); }).flatMapMany(responseMessage -> { int statusCode = RequestResponseUtils.getResponseStatusCode(responseMessage); if (statusCode != AmqpResponseCode.OK.getValue()) { return Mono.error(ExceptionUtil.amqpResponseCodeToException(statusCode, "Could not renew the lock.", getErrorContext())); } return Flux.fromIterable(messageSerializer.deserializeList(responseMessage, Instant.class)); })); } /** * Creates an AMQP message with the required application properties. * * @param operation Management operation to perform (ie. peek, update-disposition, etc.) * @param linkName Name of receiver link associated with operation. * * @return An AMQP message with the required headers. */ private Message createManagementMessage(String operation, String linkName) { final Duration serverTimeout = MessageUtils.adjustServerTimeout(operationTimeout); final Map<String, Object> applicationProperties = new HashMap<>(); applicationProperties.put(MANAGEMENT_OPERATION_KEY, operation); applicationProperties.put(SERVER_TIMEOUT, serverTimeout.toMillis()); if (linkName != null && !linkName.isEmpty()) { applicationProperties.put(ASSOCIATED_LINK_NAME_KEY, linkName); } final Message message = Proton.message(); message.setApplicationProperties(new ApplicationProperties(applicationProperties)); return message; } private AmqpErrorContext getErrorContext() { return new SessionErrorContext(fullyQualifiedNamespace, entityPath); } /** * {@inheritDoc} */ @Override public void close() { if (isDisposed) { return; } isDisposed = true; tokenManager.close(); } }
https://github.com/Azure/azure-sdk-for-java/issues/9193
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat(() -> true) .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(Assertions::assertNotNull) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken())
void renewMessageLock() { Duration renewAfterSeconds = Duration.ofSeconds(1); long takeTimeToProcessMessageMillis = 10000; final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, "id-1", 0); AtomicReference<Integer> renewMessageLockCounter = new AtomicReference<>(0); StepVerifier.create(sender.send(message).thenMany(receiverManual.receive() .take(1) .delayElements(renewAfterSeconds) .map(receivedMessage -> { Disposable disposable = receiverManual.renewMessageLock(receivedMessage.getLockToken()) .repeat() .delayElements(renewAfterSeconds) .doOnNext(instant -> { if (instant != null) { logger.info(" Received new refresh time " + instant); renewMessageLockCounter.set(renewMessageLockCounter.get() + 1); } }) .subscribe(); try { Thread.sleep(takeTimeToProcessMessageMillis); } catch (InterruptedException ignored) { } disposable.dispose(); return receivedMessage; }))) .assertNext(receivedMessage -> { Assertions.assertNotNull(receivedMessage.getLockedUntil()); }) .verifyComplete(); Assertions.assertTrue(renewMessageLockCounter.get() > 0); }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
class ServiceBusReceiverAsyncClientIntegrationTest extends IntegrationTestBase { private ServiceBusReceiverAsyncClient receiver; private ServiceBusReceiverAsyncClient receiverManual; private ServiceBusSenderAsyncClient sender; private ReceiveMessageOptions receiveMessageOptions; private ReceiveMessageOptions receiveMessageOptionsManual; ServiceBusReceiverAsyncClientIntegrationTest() { super(new ClientLogger(ServiceBusReceiverAsyncClientIntegrationTest.class)); receiveMessageOptions = new ReceiveMessageOptions().setAutoComplete(true); receiveMessageOptionsManual = new ReceiveMessageOptions().setAutoComplete(false); } @Override protected void beforeTest() { sender = createBuilder().buildAsyncSenderClient(); receiver = createBuilder() .receiveMessageOptions(receiveMessageOptions) .buildAsyncReceiverClient(); receiverManual = createBuilder() .receiveMessageOptions(receiveMessageOptionsManual) .buildAsyncReceiverClient(); } @Override protected void afterTest() { dispose(receiver, receiverManual, sender); } /** * Verifies that we can send and receive a message. */ @Test void receiveMessageAutoComplete() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).thenMany(receiver.receive().take(1))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekMessage() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek())) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a message. */ @Test void peekFromSequenceNumberMessage() { final long fromSequenceNumber = 1; final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); StepVerifier.create(sender.send(message).then(receiver.peek(fromSequenceNumber))) .assertNext(receivedMessage -> { Assertions.assertEquals(contents, new String(receivedMessage.getBody())); Assertions.assertTrue(receivedMessage.getProperties().containsKey(MESSAGE_TRACKING_ID)); }) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessages() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can send and peek a batch of messages. */ @Test void peekBatchMessagesFromSequence() { final String messageId = UUID.randomUUID().toString(); final String contents = "Some-contents"; final ServiceBusMessage message = TestUtils.getServiceBusMessage(contents, messageId, 0); int maxMessages = 2; int fromSequenceNumber = 1; StepVerifier.create(Mono.when(sender.send(message), sender.send(message)) .thenMany(receiver.peekBatch(maxMessages, fromSequenceNumber))) .expectNextCount(maxMessages) .verifyComplete(); } /** * Verifies that we can renew message lock. */ @Test }
`headerSubstituations` is instantiated to an empty `List` and will only be added to, will never be null.
public Iterable<HttpHeader> setHeaders(Object[] swaggerMethodArguments) { final HttpHeaders result = new HttpHeaders(headers); for (Substitution headerSubstitution : headerSubstitutions) { final int parameterIndex = headerSubstitution.getMethodParameterIndex(); if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) { final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()]; if (methodArgument instanceof Map) { @SuppressWarnings("unchecked") final Map<String, ?> headerCollection = (Map<String, ?>) methodArgument; final String headerCollectionPrefix = headerSubstitution.getUrlParameterName(); for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) { final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey(); final String headerValue = serialize(headerCollectionEntry.getValue()); if (headerValue != null) { result.put(headerName, headerValue); } } } else { final String headerName = headerSubstitution.getUrlParameterName(); final String headerValue = serialize(methodArgument); if (headerValue != null) { result.put(headerName, headerValue); } } } } return result; }
} else {
public Iterable<HttpHeader> setHeaders(Object[] swaggerMethodArguments) { final HttpHeaders result = new HttpHeaders(headers); for (Substitution headerSubstitution : headerSubstitutions) { final int parameterIndex = headerSubstitution.getMethodParameterIndex(); if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) { final Object methodArgument = swaggerMethodArguments[headerSubstitution.getMethodParameterIndex()]; if (methodArgument instanceof Map) { @SuppressWarnings("unchecked") final Map<String, ?> headerCollection = (Map<String, ?>) methodArgument; final String headerCollectionPrefix = headerSubstitution.getUrlParameterName(); for (final Map.Entry<String, ?> headerCollectionEntry : headerCollection.entrySet()) { final String headerName = headerCollectionPrefix + headerCollectionEntry.getKey(); final String headerValue = serialize(headerCollectionEntry.getValue()); if (headerValue != null) { result.put(headerName, headerValue); } } } else { final String headerName = headerSubstitution.getUrlParameterName(); final String headerValue = serialize(methodArgument); if (headerValue != null) { result.put(headerName, headerValue); } } } } return result; }
class SwaggerMethodParser implements HttpResponseDecodeData { private final SerializerAdapter serializer; private final String rawHost; private final String fullyQualifiedMethodName; private final HttpMethod httpMethod; private final String relativePath; private final List<Substitution> hostSubstitutions = new ArrayList<>(); private final List<Substitution> pathSubstitutions = new ArrayList<>(); private final List<Substitution> querySubstitutions = new ArrayList<>(); private final List<Substitution> formSubstitutions = new ArrayList<>(); private final List<Substitution> headerSubstitutions = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders(); private final Integer bodyContentMethodParameterIndex; private final String bodyContentType; private final Type bodyJavaType; private final int[] expectedStatusCodes; private final Type returnType; private final Type returnValueWireType; private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes; private Map<Integer, UnexpectedExceptionInformation> exceptionMapping; private UnexpectedExceptionInformation defaultException; /** * Create a SwaggerMethodParser object using the provided fully qualified method name. * * @param swaggerMethod the Swagger method to parse. * @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP * request, it must be processed through the possible host substitutions. */ SwaggerMethodParser(Method swaggerMethod, String rawHost) { this.serializer = JacksonAdapter.createDefaultSerializerAdapter(); this.rawHost = rawHost; final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass(); fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName(); if (swaggerMethod.isAnnotationPresent(Get.class)) { this.httpMethod = HttpMethod.GET; this.relativePath = swaggerMethod.getAnnotation(Get.class).value(); } else if (swaggerMethod.isAnnotationPresent(Put.class)) { this.httpMethod = HttpMethod.PUT; this.relativePath = swaggerMethod.getAnnotation(Put.class).value(); } else if (swaggerMethod.isAnnotationPresent(Head.class)) { this.httpMethod = HttpMethod.HEAD; this.relativePath = swaggerMethod.getAnnotation(Head.class).value(); } else if (swaggerMethod.isAnnotationPresent(Delete.class)) { this.httpMethod = HttpMethod.DELETE; this.relativePath = swaggerMethod.getAnnotation(Delete.class).value(); } else if (swaggerMethod.isAnnotationPresent(Post.class)) { this.httpMethod = HttpMethod.POST; this.relativePath = swaggerMethod.getAnnotation(Post.class).value(); } else if (swaggerMethod.isAnnotationPresent(Patch.class)) { this.httpMethod = HttpMethod.PATCH; this.relativePath = swaggerMethod.getAnnotation(Patch.class).value(); } else { this.httpMethod = null; this.relativePath = null; final ArrayList<Class<? extends Annotation>> requiredAnnotationOptions = new ArrayList<>(); requiredAnnotationOptions.add(Get.class); requiredAnnotationOptions.add(Put.class); requiredAnnotationOptions.add(Head.class); requiredAnnotationOptions.add(Delete.class); requiredAnnotationOptions.add(Post.class); requiredAnnotationOptions.add(Patch.class); throw new MissingRequiredAnnotationException(requiredAnnotationOptions, swaggerMethod); } returnType = swaggerMethod.getGenericReturnType(); final ReturnValueWireType returnValueWireTypeAnnotation = swaggerMethod.getAnnotation(ReturnValueWireType.class); if (returnValueWireTypeAnnotation != null) { Class<?> returnValueWireType = returnValueWireTypeAnnotation.value(); if (returnValueWireType == Base64Url.class || returnValueWireType == UnixTime.class || returnValueWireType == DateTimeRfc1123.class) { this.returnValueWireType = returnValueWireType; } else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) { this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0]; } else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) { this.returnValueWireType = returnValueWireType; } else { this.returnValueWireType = null; } } else { this.returnValueWireType = null; } if (swaggerMethod.isAnnotationPresent(Headers.class)) { final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class); final String[] headers = headersAnnotation.value(); for (final String header : headers) { final int colonIndex = header.indexOf(":"); if (colonIndex >= 0) { final String headerName = header.substring(0, colonIndex).trim(); if (!headerName.isEmpty()) { final String headerValue = header.substring(colonIndex + 1).trim(); if (!headerValue.isEmpty()) { this.headers.put(headerName, headerValue); } } } } } final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class); expectedStatusCodes = expectedResponses == null ? null : expectedResponses.value(); unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class); Integer bodyContentMethodParameterIndex = null; String bodyContentType = null; Type bodyJavaType = null; final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations(); for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) { final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex]; for (final Annotation annotation : parameterAnnotations) { final Class<? extends Annotation> annotationType = annotation.annotationType(); if (annotationType.equals(HostParam.class)) { final HostParam hostParamAnnotation = (HostParam) annotation; hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex, !hostParamAnnotation.encoded())); } else if (annotationType.equals(PathParam.class)) { final PathParam pathParamAnnotation = (PathParam) annotation; pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex, !pathParamAnnotation.encoded())); } else if (annotationType.equals(QueryParam.class)) { final QueryParam queryParamAnnotation = (QueryParam) annotation; querySubstitutions.add(new Substitution(queryParamAnnotation.value(), parameterIndex, !queryParamAnnotation.encoded())); } else if (annotationType.equals(HeaderParam.class)) { final HeaderParam headerParamAnnotation = (HeaderParam) annotation; headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex, false)); } else if (annotationType.equals(BodyParam.class)) { final BodyParam bodyParamAnnotation = (BodyParam) annotation; bodyContentMethodParameterIndex = parameterIndex; bodyContentType = bodyParamAnnotation.value(); bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex]; } else if (annotationType.equals(FormParam.class)) { final FormParam formParamAnnotation = (FormParam) annotation; formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex, !formParamAnnotation.encoded())); bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED; bodyJavaType = String.class; } } } this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex; this.bodyContentType = bodyContentType; this.bodyJavaType = bodyJavaType; } /** * Get the fully qualified method that was called to invoke this HTTP request. * * @return the fully qualified method that was called to invoke this HTTP request */ public String getFullyQualifiedMethodName() { return fullyQualifiedMethodName; } /** * Get the HTTP method that will be used to complete the Swagger method's request. * * @return the HTTP method that will be used to complete the Swagger method's request */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Get the HTTP response status codes that are expected when a request is sent out for this Swagger method. If the * returned int[] is null, then all status codes less than 400 are allowed. * * @return the expected HTTP response status codes for this Swagger method or null if all status codes less than 400 * are allowed. */ @Override public int[] getExpectedStatusCodes() { return CoreUtils.clone(expectedStatusCodes); } /** * Get the scheme to use for HTTP requests for this Swagger method. * * @param swaggerMethodArguments the arguments to use for scheme/host substitutions. * @return the final host to use for HTTP requests for this Swagger method. */ public String setScheme(Object[] swaggerMethodArguments) { final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments); final String[] substitutedHostParts = substitutedHost.split(": return substitutedHostParts.length < 1 ? null : substitutedHostParts[0]; } /** * Get the host to use for HTTP requests for this Swagger method. * * @param swaggerMethodArguments the arguments to use for host substitutions * @return the final host to use for HTTP requests for this Swagger method */ public String setHost(Object[] swaggerMethodArguments) { final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments); final String[] substitutedHostParts = substitutedHost.split(": return substitutedHostParts.length < 2 ? substitutedHost : substitutedHost.split(": } /** * Get the path that will be used to complete the Swagger method's request. * * @param methodArguments the method arguments to use with the path substitutions * @return the path value with its placeholders replaced by the matching substitutions */ public String setPath(Object[] methodArguments) { return applySubstitutions(relativePath, pathSubstitutions, methodArguments); } /** * Get the encoded query parameters that have been added to this value based on the provided method arguments. * * @param swaggerMethodArguments the arguments that will be used to create the query parameters' values * @return an Iterable with the encoded query parameters */ public Iterable<EncodedParameter> setEncodedQueryParameters(Object[] swaggerMethodArguments) { return encodeParameters(swaggerMethodArguments, querySubstitutions); } private Iterable<EncodedParameter> encodeParameters(Object[] swaggerMethodArguments, List<Substitution> substitutions) { if (substitutions == null) { return Collections.emptyList(); } final List<EncodedParameter> result = new ArrayList<>(); final PercentEscaper escaper = UrlEscapers.QUERY_ESCAPER; for (Substitution substitution : substitutions) { final int parameterIndex = substitution.getMethodParameterIndex(); if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) { final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()]; String parameterValue = serialize(methodArgument); if (parameterValue != null) { if (substitution.shouldEncode()) { parameterValue = escaper.escape(parameterValue); } result.add(new EncodedParameter(substitution.getUrlParameterName(), parameterValue)); } } } return result; } /** * Get the headers that have been added to this value based on the provided method arguments. * * @param swaggerMethodArguments The arguments that will be used to create the headers' values. * @return An Iterable with the headers. */ /** * Get the {@link Context} passed into the proxy method. * * @param swaggerMethodArguments the arguments passed to the proxy method * @return the context, or {@link Context */ public Context setContext(Object[] swaggerMethodArguments) { Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class); return (context != null) ? context : Context.NONE; } /** * Get whether or not the provided response status code is one of the expected status codes for this Swagger * method. * * @param responseStatusCode the status code that was returned in the HTTP response * @param additionalAllowedStatusCodes an additional set of allowed status codes that will be merged with the * existing set of allowed status codes for this query * @return whether or not the provided response status code is one of the expected status codes for this Swagger * method */ public boolean isExpectedResponseStatusCode(int responseStatusCode, int[] additionalAllowedStatusCodes) { boolean result; if (expectedStatusCodes == null) { result = (responseStatusCode < 400); } else { result = contains(expectedStatusCodes, responseStatusCode) || contains(additionalAllowedStatusCodes, responseStatusCode); } return result; } private static boolean contains(int[] values, int searchValue) { boolean result = false; if (values != null && values.length > 0) { for (int value : values) { if (searchValue == value) { result = true; break; } } } return result; } /** * Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response * status code is not one of the expected status codes. * * If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation * will be returned. * * @param code Exception HTTP status code return from a REST API. * @return the UnexpectedExceptionInformation to generate an exception to throw or return. */ @Override public UnexpectedExceptionInformation getUnexpectedException(int code) { if (exceptionMapping == null) { exceptionMapping = processUnexpectedResponseExceptionTypes(); } return exceptionMapping.getOrDefault(code, defaultException); } /** * Get the object to be used as the value of the HTTP request. * * @param swaggerMethodArguments the method arguments to get the value object from * @return the object that will be used as the body of the HTTP request */ public Object setBody(Object[] swaggerMethodArguments) { Object result = null; if (bodyContentMethodParameterIndex != null && swaggerMethodArguments != null && 0 <= bodyContentMethodParameterIndex && bodyContentMethodParameterIndex < swaggerMethodArguments.length) { result = swaggerMethodArguments[bodyContentMethodParameterIndex]; } if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) { result = formSubstitutions.stream() .map(s -> serializeFormData(s.getUrlParameterName(), swaggerMethodArguments[s.getMethodParameterIndex()])) .collect(Collectors.joining("&")); } return result; } /** * Get the Content-Type of the body of this Swagger method. * * @return the Content-Type of the body of this Swagger method */ public String getBodyContentType() { return bodyContentType; } /** * Get the return type for the method that this object describes. * * @return the return type for the method that this object describes. */ @Override public Type getReturnType() { return returnType; } /** * Get the type of the body parameter to this method, if present. * * @return the return type of the body parameter to this method */ public Type getBodyJavaType() { return bodyJavaType; } /** * Get the type that the return value will be send across the network as. If returnValueWireType is not null, then * the raw HTTP response body will need to parsed to this type and then converted to the actual returnType. * * @return the type that the raw HTTP response body will be sent as */ @Override public Type getReturnValueWireType() { return returnValueWireType; } private String serialize(Object value) { String result = null; if (value != null) { if (value instanceof String) { result = (String) value; } else { result = serializer.serializeRaw(value); } } return result; } private String serializeFormData(String key, Object value) { String result = null; if (value != null) { if (value instanceof List<?>) { result = ((List<?>) value).stream() .map(el -> String.format("%s=%s", key, serialize(el))) .collect(Collectors.joining("&")); } else { result = String.format("%s=%s", key, serializer.serializeRaw(value)); } } return result; } private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions, Object[] methodArguments) { String result = originalValue; if (methodArguments != null) { for (Substitution substitution : substitutions) { final int substitutionParameterIndex = substitution.getMethodParameterIndex(); if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) { final Object methodArgument = methodArguments[substitutionParameterIndex]; String substitutionValue = serialize(methodArgument); if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) { substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue); } if (substitutionValue == null) { substitutionValue = ""; } result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue); } } } return result; } private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() { HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>(); for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) { UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value()); if (exceptionAnnotation.code().length == 0) { defaultException = exception; } else { for (int statusCode : exceptionAnnotation.code()) { exceptionHashMap.put(statusCode, exception); } } } if (defaultException == null) { defaultException = new UnexpectedExceptionInformation(HttpResponseException.class); } return exceptionHashMap; } }
class SwaggerMethodParser implements HttpResponseDecodeData { private final SerializerAdapter serializer; private final String rawHost; private final String fullyQualifiedMethodName; private final HttpMethod httpMethod; private final String relativePath; private final List<Substitution> hostSubstitutions = new ArrayList<>(); private final List<Substitution> pathSubstitutions = new ArrayList<>(); private final List<Substitution> querySubstitutions = new ArrayList<>(); private final List<Substitution> formSubstitutions = new ArrayList<>(); private final List<Substitution> headerSubstitutions = new ArrayList<>(); private final HttpHeaders headers = new HttpHeaders(); private final Integer bodyContentMethodParameterIndex; private final String bodyContentType; private final Type bodyJavaType; private final int[] expectedStatusCodes; private final Type returnType; private final Type returnValueWireType; private final UnexpectedResponseExceptionType[] unexpectedResponseExceptionTypes; private Map<Integer, UnexpectedExceptionInformation> exceptionMapping; private UnexpectedExceptionInformation defaultException; /** * Create a SwaggerMethodParser object using the provided fully qualified method name. * * @param swaggerMethod the Swagger method to parse. * @param rawHost the raw host value from the @Host annotation. Before this can be used as the host value in an HTTP * request, it must be processed through the possible host substitutions. */ SwaggerMethodParser(Method swaggerMethod, String rawHost) { this.serializer = JacksonAdapter.createDefaultSerializerAdapter(); this.rawHost = rawHost; final Class<?> swaggerInterface = swaggerMethod.getDeclaringClass(); fullyQualifiedMethodName = swaggerInterface.getName() + "." + swaggerMethod.getName(); if (swaggerMethod.isAnnotationPresent(Get.class)) { this.httpMethod = HttpMethod.GET; this.relativePath = swaggerMethod.getAnnotation(Get.class).value(); } else if (swaggerMethod.isAnnotationPresent(Put.class)) { this.httpMethod = HttpMethod.PUT; this.relativePath = swaggerMethod.getAnnotation(Put.class).value(); } else if (swaggerMethod.isAnnotationPresent(Head.class)) { this.httpMethod = HttpMethod.HEAD; this.relativePath = swaggerMethod.getAnnotation(Head.class).value(); } else if (swaggerMethod.isAnnotationPresent(Delete.class)) { this.httpMethod = HttpMethod.DELETE; this.relativePath = swaggerMethod.getAnnotation(Delete.class).value(); } else if (swaggerMethod.isAnnotationPresent(Post.class)) { this.httpMethod = HttpMethod.POST; this.relativePath = swaggerMethod.getAnnotation(Post.class).value(); } else if (swaggerMethod.isAnnotationPresent(Patch.class)) { this.httpMethod = HttpMethod.PATCH; this.relativePath = swaggerMethod.getAnnotation(Patch.class).value(); } else { this.httpMethod = null; this.relativePath = null; final ArrayList<Class<? extends Annotation>> requiredAnnotationOptions = new ArrayList<>(); requiredAnnotationOptions.add(Get.class); requiredAnnotationOptions.add(Put.class); requiredAnnotationOptions.add(Head.class); requiredAnnotationOptions.add(Delete.class); requiredAnnotationOptions.add(Post.class); requiredAnnotationOptions.add(Patch.class); throw new MissingRequiredAnnotationException(requiredAnnotationOptions, swaggerMethod); } returnType = swaggerMethod.getGenericReturnType(); final ReturnValueWireType returnValueWireTypeAnnotation = swaggerMethod.getAnnotation(ReturnValueWireType.class); if (returnValueWireTypeAnnotation != null) { Class<?> returnValueWireType = returnValueWireTypeAnnotation.value(); if (returnValueWireType == Base64Url.class || returnValueWireType == UnixTime.class || returnValueWireType == DateTimeRfc1123.class) { this.returnValueWireType = returnValueWireType; } else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, List.class)) { this.returnValueWireType = returnValueWireType.getGenericInterfaces()[0]; } else if (TypeUtil.isTypeOrSubTypeOf(returnValueWireType, Page.class)) { this.returnValueWireType = returnValueWireType; } else { this.returnValueWireType = null; } } else { this.returnValueWireType = null; } if (swaggerMethod.isAnnotationPresent(Headers.class)) { final Headers headersAnnotation = swaggerMethod.getAnnotation(Headers.class); final String[] headers = headersAnnotation.value(); for (final String header : headers) { final int colonIndex = header.indexOf(":"); if (colonIndex >= 0) { final String headerName = header.substring(0, colonIndex).trim(); if (!headerName.isEmpty()) { final String headerValue = header.substring(colonIndex + 1).trim(); if (!headerValue.isEmpty()) { this.headers.put(headerName, headerValue); } } } } } final ExpectedResponses expectedResponses = swaggerMethod.getAnnotation(ExpectedResponses.class); expectedStatusCodes = expectedResponses == null ? null : expectedResponses.value(); unexpectedResponseExceptionTypes = swaggerMethod.getAnnotationsByType(UnexpectedResponseExceptionType.class); Integer bodyContentMethodParameterIndex = null; String bodyContentType = null; Type bodyJavaType = null; final Annotation[][] allParametersAnnotations = swaggerMethod.getParameterAnnotations(); for (int parameterIndex = 0; parameterIndex < allParametersAnnotations.length; ++parameterIndex) { final Annotation[] parameterAnnotations = swaggerMethod.getParameterAnnotations()[parameterIndex]; for (final Annotation annotation : parameterAnnotations) { final Class<? extends Annotation> annotationType = annotation.annotationType(); if (annotationType.equals(HostParam.class)) { final HostParam hostParamAnnotation = (HostParam) annotation; hostSubstitutions.add(new Substitution(hostParamAnnotation.value(), parameterIndex, !hostParamAnnotation.encoded())); } else if (annotationType.equals(PathParam.class)) { final PathParam pathParamAnnotation = (PathParam) annotation; pathSubstitutions.add(new Substitution(pathParamAnnotation.value(), parameterIndex, !pathParamAnnotation.encoded())); } else if (annotationType.equals(QueryParam.class)) { final QueryParam queryParamAnnotation = (QueryParam) annotation; querySubstitutions.add(new Substitution(queryParamAnnotation.value(), parameterIndex, !queryParamAnnotation.encoded())); } else if (annotationType.equals(HeaderParam.class)) { final HeaderParam headerParamAnnotation = (HeaderParam) annotation; headerSubstitutions.add(new Substitution(headerParamAnnotation.value(), parameterIndex, false)); } else if (annotationType.equals(BodyParam.class)) { final BodyParam bodyParamAnnotation = (BodyParam) annotation; bodyContentMethodParameterIndex = parameterIndex; bodyContentType = bodyParamAnnotation.value(); bodyJavaType = swaggerMethod.getGenericParameterTypes()[parameterIndex]; } else if (annotationType.equals(FormParam.class)) { final FormParam formParamAnnotation = (FormParam) annotation; formSubstitutions.add(new Substitution(formParamAnnotation.value(), parameterIndex, !formParamAnnotation.encoded())); bodyContentType = ContentType.APPLICATION_X_WWW_FORM_URLENCODED; bodyJavaType = String.class; } } } this.bodyContentMethodParameterIndex = bodyContentMethodParameterIndex; this.bodyContentType = bodyContentType; this.bodyJavaType = bodyJavaType; } /** * Get the fully qualified method that was called to invoke this HTTP request. * * @return the fully qualified method that was called to invoke this HTTP request */ public String getFullyQualifiedMethodName() { return fullyQualifiedMethodName; } /** * Get the HTTP method that will be used to complete the Swagger method's request. * * @return the HTTP method that will be used to complete the Swagger method's request */ public HttpMethod getHttpMethod() { return httpMethod; } /** * Get the HTTP response status codes that are expected when a request is sent out for this Swagger method. If the * returned int[] is null, then all status codes less than 400 are allowed. * * @return the expected HTTP response status codes for this Swagger method or null if all status codes less than 400 * are allowed. */ @Override public int[] getExpectedStatusCodes() { return CoreUtils.clone(expectedStatusCodes); } /** * Get the scheme to use for HTTP requests for this Swagger method. * * @param swaggerMethodArguments the arguments to use for scheme/host substitutions. * @return the final host to use for HTTP requests for this Swagger method. */ public String setScheme(Object[] swaggerMethodArguments) { final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments); final String[] substitutedHostParts = substitutedHost.split(": return substitutedHostParts.length < 1 ? null : substitutedHostParts[0]; } /** * Get the host to use for HTTP requests for this Swagger method. * * @param swaggerMethodArguments the arguments to use for host substitutions * @return the final host to use for HTTP requests for this Swagger method */ public String setHost(Object[] swaggerMethodArguments) { final String substitutedHost = applySubstitutions(rawHost, hostSubstitutions, swaggerMethodArguments); final String[] substitutedHostParts = substitutedHost.split(": return substitutedHostParts.length < 2 ? substitutedHost : substitutedHost.split(": } /** * Get the path that will be used to complete the Swagger method's request. * * @param methodArguments the method arguments to use with the path substitutions * @return the path value with its placeholders replaced by the matching substitutions */ public String setPath(Object[] methodArguments) { return applySubstitutions(relativePath, pathSubstitutions, methodArguments); } /** * Get the encoded query parameters that have been added to this value based on the provided method arguments. * * @param swaggerMethodArguments the arguments that will be used to create the query parameters' values * @return an Iterable with the encoded query parameters */ public Iterable<EncodedParameter> setEncodedQueryParameters(Object[] swaggerMethodArguments) { return encodeParameters(swaggerMethodArguments, querySubstitutions); } private Iterable<EncodedParameter> encodeParameters(Object[] swaggerMethodArguments, List<Substitution> substitutions) { if (substitutions == null) { return Collections.emptyList(); } final List<EncodedParameter> result = new ArrayList<>(); final PercentEscaper escaper = UrlEscapers.QUERY_ESCAPER; for (Substitution substitution : substitutions) { final int parameterIndex = substitution.getMethodParameterIndex(); if (0 <= parameterIndex && parameterIndex < swaggerMethodArguments.length) { final Object methodArgument = swaggerMethodArguments[substitution.getMethodParameterIndex()]; String parameterValue = serialize(methodArgument); if (parameterValue != null) { if (substitution.shouldEncode()) { parameterValue = escaper.escape(parameterValue); } result.add(new EncodedParameter(substitution.getUrlParameterName(), parameterValue)); } } } return result; } /** * Get the headers that have been added to this value based on the provided method arguments. * * @param swaggerMethodArguments The arguments that will be used to create the headers' values. * @return An Iterable with the headers. */ /** * Get the {@link Context} passed into the proxy method. * * @param swaggerMethodArguments the arguments passed to the proxy method * @return the context, or {@link Context */ public Context setContext(Object[] swaggerMethodArguments) { Context context = CoreUtils.findFirstOfType(swaggerMethodArguments, Context.class); return (context != null) ? context : Context.NONE; } /** * Get whether or not the provided response status code is one of the expected status codes for this Swagger * method. * * @param responseStatusCode the status code that was returned in the HTTP response * @param additionalAllowedStatusCodes an additional set of allowed status codes that will be merged with the * existing set of allowed status codes for this query * @return whether or not the provided response status code is one of the expected status codes for this Swagger * method */ public boolean isExpectedResponseStatusCode(int responseStatusCode, int[] additionalAllowedStatusCodes) { boolean result; if (expectedStatusCodes == null) { result = (responseStatusCode < 400); } else { result = contains(expectedStatusCodes, responseStatusCode) || contains(additionalAllowedStatusCodes, responseStatusCode); } return result; } private static boolean contains(int[] values, int searchValue) { boolean result = false; if (values != null && values.length > 0) { for (int value : values) { if (searchValue == value) { result = true; break; } } } return result; } /** * Get the {@link UnexpectedExceptionInformation} that will be used to generate a RestException if the HTTP response * status code is not one of the expected status codes. * * If an UnexpectedExceptionInformation is not found for the status code the default UnexpectedExceptionInformation * will be returned. * * @param code Exception HTTP status code return from a REST API. * @return the UnexpectedExceptionInformation to generate an exception to throw or return. */ @Override public UnexpectedExceptionInformation getUnexpectedException(int code) { if (exceptionMapping == null) { exceptionMapping = processUnexpectedResponseExceptionTypes(); } return exceptionMapping.getOrDefault(code, defaultException); } /** * Get the object to be used as the value of the HTTP request. * * @param swaggerMethodArguments the method arguments to get the value object from * @return the object that will be used as the body of the HTTP request */ public Object setBody(Object[] swaggerMethodArguments) { Object result = null; if (bodyContentMethodParameterIndex != null && swaggerMethodArguments != null && 0 <= bodyContentMethodParameterIndex && bodyContentMethodParameterIndex < swaggerMethodArguments.length) { result = swaggerMethodArguments[bodyContentMethodParameterIndex]; } if (!CoreUtils.isNullOrEmpty(formSubstitutions) && swaggerMethodArguments != null) { result = formSubstitutions.stream() .map(s -> serializeFormData(s.getUrlParameterName(), swaggerMethodArguments[s.getMethodParameterIndex()])) .collect(Collectors.joining("&")); } return result; } /** * Get the Content-Type of the body of this Swagger method. * * @return the Content-Type of the body of this Swagger method */ public String getBodyContentType() { return bodyContentType; } /** * Get the return type for the method that this object describes. * * @return the return type for the method that this object describes. */ @Override public Type getReturnType() { return returnType; } /** * Get the type of the body parameter to this method, if present. * * @return the return type of the body parameter to this method */ public Type getBodyJavaType() { return bodyJavaType; } /** * Get the type that the return value will be send across the network as. If returnValueWireType is not null, then * the raw HTTP response body will need to parsed to this type and then converted to the actual returnType. * * @return the type that the raw HTTP response body will be sent as */ @Override public Type getReturnValueWireType() { return returnValueWireType; } private String serialize(Object value) { String result = null; if (value != null) { if (value instanceof String) { result = (String) value; } else { result = serializer.serializeRaw(value); } } return result; } private String serializeFormData(String key, Object value) { String result = null; if (value != null) { if (value instanceof List<?>) { result = ((List<?>) value).stream() .map(el -> String.format("%s=%s", key, serialize(el))) .collect(Collectors.joining("&")); } else { result = String.format("%s=%s", key, serializer.serializeRaw(value)); } } return result; } private String applySubstitutions(String originalValue, Iterable<Substitution> substitutions, Object[] methodArguments) { String result = originalValue; if (methodArguments != null) { for (Substitution substitution : substitutions) { final int substitutionParameterIndex = substitution.getMethodParameterIndex(); if (0 <= substitutionParameterIndex && substitutionParameterIndex < methodArguments.length) { final Object methodArgument = methodArguments[substitutionParameterIndex]; String substitutionValue = serialize(methodArgument); if (substitutionValue != null && !substitutionValue.isEmpty() && substitution.shouldEncode()) { substitutionValue = UrlEscapers.PATH_ESCAPER.escape(substitutionValue); } if (substitutionValue == null) { substitutionValue = ""; } result = result.replace("{" + substitution.getUrlParameterName() + "}", substitutionValue); } } } return result; } private Map<Integer, UnexpectedExceptionInformation> processUnexpectedResponseExceptionTypes() { HashMap<Integer, UnexpectedExceptionInformation> exceptionHashMap = new HashMap<>(); for (UnexpectedResponseExceptionType exceptionAnnotation : unexpectedResponseExceptionTypes) { UnexpectedExceptionInformation exception = new UnexpectedExceptionInformation(exceptionAnnotation.value()); if (exceptionAnnotation.code().length == 0) { defaultException = exception; } else { for (int statusCode : exceptionAnnotation.code()) { exceptionHashMap.put(statusCode, exception); } } } if (defaultException == null) { defaultException = new UnexpectedExceptionInformation(HttpResponseException.class); } return exceptionHashMap; } }
Is this using the same exception message as credentials in AAD use? It would be nice to turn it into a proper sentence here and file an issue for the other locations.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); } context.getHttpRequest().setHeader(API_KEY, this.apiKey.getApiKey()); return next.process(); }
return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme"));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Search api-key credentials require a URL using the HTTPS protocol " + "scheme.")); } context.getHttpRequest().setHeader(API_KEY, this.apiKey.getApiKey()); return next.process(); }
class SearchApiKeyPipelinePolicy implements HttpPipelinePolicy { private static final String API_KEY = "api-key"; private final SearchApiKeyCredential apiKey; /** * Constructor * * @param apiKey Azure Cognitive Search service api admin or query key * @throws IllegalArgumentException when the api key is an empty string */ public SearchApiKeyPipelinePolicy(SearchApiKeyCredential apiKey) { Objects.requireNonNull(apiKey, "'apiKey' cannot be null."); this.apiKey = apiKey; } @Override }
class SearchApiKeyPipelinePolicy implements HttpPipelinePolicy { private static final String API_KEY = "api-key"; private final SearchApiKeyCredential apiKey; /** * Constructor * * @param apiKey Azure Cognitive Search service api admin or query key * @throws IllegalArgumentException when the api key is an empty string */ public SearchApiKeyPipelinePolicy(SearchApiKeyCredential apiKey) { Objects.requireNonNull(apiKey, "'apiKey' cannot be null."); this.apiKey = apiKey; } @Override }
Thanks for catching this.
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme")); } context.getHttpRequest().setHeader(API_KEY, this.apiKey.getApiKey()); return next.process(); }
return Mono.error(new RuntimeException("token credentials require a URL using the HTTPS protocol scheme"));
public Mono<HttpResponse> process(HttpPipelineCallContext context, HttpPipelineNextPolicy next) { if ("http".equals(context.getHttpRequest().getUrl().getProtocol())) { return Mono.error(new RuntimeException("Search api-key credentials require a URL using the HTTPS protocol " + "scheme.")); } context.getHttpRequest().setHeader(API_KEY, this.apiKey.getApiKey()); return next.process(); }
class SearchApiKeyPipelinePolicy implements HttpPipelinePolicy { private static final String API_KEY = "api-key"; private final SearchApiKeyCredential apiKey; /** * Constructor * * @param apiKey Azure Cognitive Search service api admin or query key * @throws IllegalArgumentException when the api key is an empty string */ public SearchApiKeyPipelinePolicy(SearchApiKeyCredential apiKey) { Objects.requireNonNull(apiKey, "'apiKey' cannot be null."); this.apiKey = apiKey; } @Override }
class SearchApiKeyPipelinePolicy implements HttpPipelinePolicy { private static final String API_KEY = "api-key"; private final SearchApiKeyCredential apiKey; /** * Constructor * * @param apiKey Azure Cognitive Search service api admin or query key * @throws IllegalArgumentException when the api key is an empty string */ public SearchApiKeyPipelinePolicy(SearchApiKeyCredential apiKey) { Objects.requireNonNull(apiKey, "'apiKey' cannot be null."); this.apiKey = apiKey; } @Override }
Is this exception message meant to be the same as the one above?
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
"Shared token cache is unavailable in this environment.", null, t));
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
The defer isn't needed here.
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
.switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> {
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Should this use a future supplier as below?
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters))
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Does account here have to be non-null? If it can be null, could the if/else block be merged to always pass `account`?
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build();
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Need to use `Exceptions.propagate` here.
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
throw logger.logExceptionAsWarning(new RuntimeException(e));
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Removed.
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
.switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> {
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Yeah we should
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters))
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Unfortunately in the first builder overload the account is required to be non-null.
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build();
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
But it does seem like I can add account afterwards
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build();
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Reorganized a little bit to avoid creating 2 parameters upfront
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); }
parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build();
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
They are indeed the same - just wrapping in different exceptions to be handled differently downstream.
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { return null; } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException( "Shared token cache is unavailable in this environment.", t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException( "Shared token cache is unavailable in this environment.", null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
"Shared token cache is unavailable in this environment.", null, t));
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with username " + "and password", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { SilentParameters parameters; SilentParameters forceParameters; if (account != null) { parameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes()), account) .forceRefresh(true).build(); } else { parameters = SilentParameters.builder(new HashSet<>(request.getScopes())).build(); forceParameters = SilentParameters.builder(new HashSet<>(request.getScopes())).forceRefresh(true).build(); } return Mono.defer(() -> { try { return Mono.fromFuture(getPublicClientApplication(false).acquireTokenSilently(parameters)) .map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.defer(() -> Mono.fromFuture(() -> { try { return getPublicClientApplication(false).acquireTokenSilently(forceParameters); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new RuntimeException(e)); } } ).map(result -> new MsalToken(result, options)))); } catch (MalformedURLException e) { return Mono.error(e); } }); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with device code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorResume(t -> Mono.error(new ClientAuthenticationException("Failed to acquire token with " + "authorization code", null, t))).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorResume(t -> Mono.error(new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t))) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.size() == 0) { if (username == null) { return Mono.error(new CredentialUnavailableException("No accounts were discovered in the " + "shared token cache. To fix, authenticate through tooling supporting azure " + "developer sign on.")); } else { return Mono.error(new CredentialUnavailableException(String.format("User account '%s' was " + "not found in the shared token cache. Discovered Accounts: [ '%s' ]", username, set.stream().map(IAccount::username).distinct() .collect(Collectors.joining(", "))))); } } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new CredentialUnavailableException("Multiple accounts were discovered " + "in the shared token cache. To fix, set the AZURE_USERNAME and AZURE_TENANT_ID " + "environment variable to the preferred username, or specify it when " + "constructing SharedTokenCacheCredential.")); } else { return Mono.error(new CredentialUnavailableException("Multiple entries for the user " + "account " + username + " were found in the shared token cache. This is not " + "currently supported by the SharedTokenCacheCredential.")); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Since you're using futures, it may be easier to follow using: ```java var completableFuture = new CompletableFuture<MsalToken>(); completableFuture.completeExceptionally(logger.logExceptionAsError(Exceptions.propagate(e)); return completableFuture; ```
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
throw logger.logExceptionAsError(Exceptions.propagate(e));
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be providedfor user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.size() == 0) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.size() == 0) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
providedfor -> provided for
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be providedfor user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
"A non-null value for client ID must be providedfor user authentication."));
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.size() == 0) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.size() == 0) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Thanks Connie for the tip but in this code the exception is thrown from creating the future, not from executing it.
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
throw logger.logExceptionAsError(Exceptions.propagate(e));
public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be providedfor user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.size() == 0) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.size() == 0) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
This method is called from numerous methods on the IdentityClient some which pass `sharedTokenCacheCredential` as `true` and some as `false`. Whichever calls this method first will cache the publicClientApplication and then all subsequent calls will effectively ignore the `sharedTokenCacheCredential` parameter. I'm guessing this doesn't matter in practice because certain credentials only call certain methods, and each credential has it's own instance of `IdentityClient`, and `IdentityClient` is internal. However, this makes the functionality of this class and the classes that use it interdependent in a non-obvious way which could easily be overlooked if we try to make optimizations like sharing an instance of `IdentityClient`. I think we should consider refactoring this.
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
return publicClientApplication;
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.isEmpty()) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
This is not thread safe. If two clients using the same credential call get token at the same time it's possible that multiple threads attempt to initialize `publicClientApplication` at the same time. In this case they might each get different instances and any tokens cached on any instances other than the final one will be lost.
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
this.publicClientApplication = publicClientApplicationBuilder.build();
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.isEmpty()) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Opened an issue #10675
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
this.publicClientApplication = publicClientApplicationBuilder.build();
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.isEmpty()) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Opened an issue #10675
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
return publicClientApplication;
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.isEmpty()) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
Resolving as separate issues opened
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
this.publicClientApplication = publicClientApplicationBuilder.build();
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.isEmpty()) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
This method is only called once per IdentityClient and there's exactly one IdentityClient instance per credential. Yes it can have nicer designs, as something we can do for #10675
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/organizations/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
return publicClientApplication;
private PublicClientApplication getPublicClientApplication(boolean sharedTokenCacheCredential) { if (publicClientApplication != null) { return publicClientApplication; } else if (clientId == null) { throw logger.logExceptionAsError(new IllegalArgumentException( "A non-null value for client ID must be provided for user authentication.")); } else { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; PublicClientApplication.Builder publicClientApplicationBuilder = PublicClientApplication.builder(clientId); try { publicClientApplicationBuilder = publicClientApplicationBuilder.authority(authorityUrl); } catch (MalformedURLException e) { throw logger.logExceptionAsWarning(new IllegalStateException(e)); } HttpPipeline httpPipeline = options.getHttpPipeline(); if (httpPipeline != null) { httpPipelineAdapter = new HttpPipelineAdapter(httpPipeline); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else { HttpClient httpClient = options.getHttpClient(); if (httpClient != null) { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(httpClient)); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { publicClientApplicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } else { httpPipelineAdapter = new HttpPipelineAdapter(setupPipeline(HttpClient.createDefault())); publicClientApplicationBuilder.httpClient(httpPipelineAdapter); } } if (options.getExecutorService() != null) { publicClientApplicationBuilder.executorService(options.getExecutorService()); } if (options.isSharedTokenCacheEnabled()) { try { publicClientApplicationBuilder.setTokenCacheAccessAspect( new PersistenceTokenCacheAccessAspect(options.getPersistenceSettings())); } catch (Throwable t) { String message = "Shared token cache is unavailable in this environment."; if (sharedTokenCacheCredential) { throw logger.logExceptionAsError(new CredentialUnavailableException(message, t)); } else { throw logger.logExceptionAsError(new ClientAuthenticationException(message, null, t)); } } } this.publicClientApplication = publicClientApplicationBuilder.build(); return this.publicClientApplication; } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "common"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<AccessToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } if (CoreUtils.isNullOrEmpty(username)) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts were found in the cache. Use " + "username and tenant id to disambiguate.")); } if (accounts.size() != 1) { if (accounts.isEmpty()) { return Mono.error(new CredentialUnavailableException( String.format("SharedTokenCacheCredential authentication " + "unavailable. No account matching the specified username %s was found " + "in the cache.", username))); } else { return Mono.error(new CredentialUnavailableException(String.format( "SharedTokenCacheCredential authentication unavailable. Multiple accounts " + "matching the specified username %s were found in the cache.", username))); } } requestedAccount = accounts.values().iterator().next(); return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
class IdentityClient { private static final SerializerAdapter SERIALIZER_ADAPTER = JacksonAdapter.createDefaultSerializerAdapter(); private static final Random RANDOM = new Random(); private static final String WINDOWS_STARTER = "cmd.exe"; private static final String LINUX_MAC_STARTER = "/bin/sh"; private static final String WINDOWS_SWITCHER = "/c"; private static final String LINUX_MAC_SWITCHER = "-c"; private static final String WINDOWS_PROCESS_ERROR_MESSAGE = "'az' is not recognized"; private static final String LINUX_MAC_PROCESS_ERROR_MESSAGE = "(.*)az:(.*)not found"; private static final String DEFAULT_WINDOWS_SYSTEM_ROOT = System.getenv("SystemRoot"); private static final String DEFAULT_MAC_LINUX_PATH = "/bin/"; private final ClientLogger logger = new ClientLogger(IdentityClient.class); private final IdentityClientOptions options; private PublicClientApplication publicClientApplication; private final String tenantId; private final String clientId; private HttpPipelineAdapter httpPipelineAdapter; /** * Creates an IdentityClient with the given options. * * @param tenantId the tenant ID of the application. * @param clientId the client ID of the application. * @param options the options configuring the client. */ IdentityClient(String tenantId, String clientId, IdentityClientOptions options) { if (tenantId == null) { tenantId = "organizations"; } if (options == null) { options = new IdentityClientOptions(); } this.tenantId = tenantId; this.clientId = clientId; this.options = options; } public Mono<MsalToken> authenticateWithIntelliJ(TokenRequestContext request) { try { IntelliJCacheAccessor cacheAccessor = new IntelliJCacheAccessor(options.getIntelliJKeePassDatabasePath()); IntelliJAuthMethodDetails authDetails = cacheAccessor.getAuthDetailsIfAvailable(); String authType = authDetails.getAuthMethod(); if (authType.equalsIgnoreCase("SP")) { Map<String, String> spDetails = cacheAccessor .getIntellijServicePrincipalDetails(authDetails.getCredFilePath()); String authorityUrl = spDetails.get("authURL") + spDetails.get("tenant"); try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(spDetails.get("client"), ClientCredentialFactory.createFromSecret(spDetails.get("key"))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } else if (authType.equalsIgnoreCase("DC")) { JsonNode intelliJCredentials = cacheAccessor.getDeviceCodeCredentials(); String refreshToken = intelliJCredentials.get("refreshToken").textValue(); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), refreshToken) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } else { throw logger.logExceptionAsError(new CredentialUnavailableException( "IntelliJ Authentication not available." + " Please login with Azure Tools for IntelliJ plugin in the IDE.")); } } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with Azure CLI. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithAzureCli(TokenRequestContext request) { String azCommand = "az account get-access-token --output json --resource "; StringBuilder command = new StringBuilder(); command.append(azCommand); String scopes = ScopeUtil.scopesToResource(request.getScopes()); try { ScopeUtil.validateScope(scopes); } catch (IllegalArgumentException ex) { return Mono.error(logger.logExceptionAsError(ex)); } command.append(scopes); AccessToken token = null; BufferedReader reader = null; try { String starter; String switcher; if (isWindowsPlatform()) { starter = WINDOWS_STARTER; switcher = WINDOWS_SWITCHER; } else { starter = LINUX_MAC_STARTER; switcher = LINUX_MAC_SWITCHER; } ProcessBuilder builder = new ProcessBuilder(starter, switcher, command.toString()); String workingDirectory = getSafeWorkingDirectory(); if (workingDirectory != null) { builder.directory(new File(workingDirectory)); } else { throw logger.logExceptionAsError(new IllegalStateException("A Safe Working directory could not be" + " found to execute CLI command from.")); } builder.redirectErrorStream(true); Process process = builder.start(); reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8")); String line; StringBuilder output = new StringBuilder(); while (true) { line = reader.readLine(); if (line == null) { break; } if (line.startsWith(WINDOWS_PROCESS_ERROR_MESSAGE) || line.matches(LINUX_MAC_PROCESS_ERROR_MESSAGE)) { throw logger.logExceptionAsError( new CredentialUnavailableException("Azure CLI not installed")); } output.append(line); } String processOutput = output.toString(); process.waitFor(10, TimeUnit.SECONDS); if (process.exitValue() != 0) { if (processOutput.length() > 0) { String redactedOutput = redactInfo("\"accessToken\": \"(.*?)(\"|$)", processOutput); if (redactedOutput.contains("az login") || redactedOutput.contains("az account set")) { throw logger.logExceptionAsError( new CredentialUnavailableException("Please run 'az login' to set up account")); } throw logger.logExceptionAsError(new ClientAuthenticationException(redactedOutput, null)); } else { throw logger.logExceptionAsError( new ClientAuthenticationException("Failed to invoke Azure CLI ", null)); } } Map<String, String> objectMap = SERIALIZER_ADAPTER.deserialize(processOutput, Map.class, SerializerEncoding.JSON); String accessToken = objectMap.get("accessToken"); String time = objectMap.get("expiresOn"); String timeToSecond = time.substring(0, time.indexOf(".")); String timeJoinedWithT = String.join("T", timeToSecond.split(" ")); OffsetDateTime expiresOn = LocalDateTime.parse(timeJoinedWithT, DateTimeFormatter.ISO_LOCAL_DATE_TIME) .atZone(ZoneId.systemDefault()) .toOffsetDateTime().withOffsetSameInstant(ZoneOffset.UTC); token = new IdentityToken(accessToken, expiresOn, options); } catch (IOException | InterruptedException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } catch (RuntimeException e) { return Mono.error(logger.logExceptionAsError(e)); } finally { try { if (reader != null) { reader.close(); } } catch (IOException ex) { return Mono.error(logger.logExceptionAsError(new IllegalStateException(ex))); } } return Mono.just(token); } /** * Asynchronously acquire a token from Active Directory with a client secret. * * @param clientSecret the client secret of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithClientSecret(String clientSecret, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromSecret(clientSecret)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (MalformedURLException e) { return Mono.error(e); } } private HttpPipeline setupPipeline(HttpClient httpClient) { List<HttpPipelinePolicy> policies = new ArrayList<>(); HttpLogOptions httpLogOptions = new HttpLogOptions(); HttpPolicyProviders.addBeforeRetryPolicies(policies); policies.add(new RetryPolicy()); HttpPolicyProviders.addAfterRetryPolicies(policies); policies.add(new HttpLoggingPolicy(httpLogOptions)); return new HttpPipelineBuilder().httpClient(httpClient) .policies(policies.toArray(new HttpPipelinePolicy[0])).build(); } /** * Asynchronously acquire a token from Active Directory with a PKCS12 certificate. * * @param pfxCertificatePath the path to the PKCS12 certificate of the application * @param pfxCertificatePassword the password protecting the PFX certificate * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPfxCertificate(String pfxCertificatePath, String pfxCertificatePassword, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return Mono.fromCallable(() -> { ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( new FileInputStream(pfxCertificatePath), pfxCertificatePassword)) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } return applicationBuilder.build(); }).flatMap(application -> Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())).build()))) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with a PEM certificate. * * @param pemCertificatePath the path to the PEM certificate of the application * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateWithPemCertificate(String pemCertificatePath, TokenRequestContext request) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; try { byte[] pemCertificateBytes = Files.readAllBytes(Paths.get(pemCertificatePath)); ConfidentialClientApplication.Builder applicationBuilder = ConfidentialClientApplication.builder(clientId, ClientCredentialFactory.createFromCertificate( CertificateUtil.privateKeyFromPem(pemCertificateBytes), CertificateUtil.publicKeyFromPem(pemCertificateBytes))) .authority(authorityUrl); if (httpPipelineAdapter != null) { applicationBuilder.httpClient(httpPipelineAdapter); } else if (options.getProxyOptions() != null) { applicationBuilder.proxy(proxyOptionsToJavaNetProxy(options.getProxyOptions())); } if (options.getExecutorService() != null) { applicationBuilder.executorService(options.getExecutorService()); } ConfidentialClientApplication application = applicationBuilder.build(); return Mono.fromFuture(application.acquireToken( ClientCredentialParameters.builder(new HashSet<>(request.getScopes())) .build())) .map(ar -> new MsalToken(ar, options)); } catch (IOException e) { return Mono.error(e); } } /** * Asynchronously acquire a token from Active Directory with a username and a password. * * @param request the details of the token request * @param username the username of the user * @param password the password of the user * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithUsernamePassword(TokenRequestContext request, String username, String password) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( UserNamePasswordParameters.builder(new HashSet<>(request.getScopes()), username, password.toCharArray()) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with username and password", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from the currently logged in client. * * @param request the details of the token request * @param account the account used to login to acquire the last token * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithMsalAccount(TokenRequestContext request, IAccount account) { return Mono.defer(() -> Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder parametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())); if (account != null) { parametersBuilder = parametersBuilder.account(account); } try { return getPublicClientApplication(false) .acquireTokenSilently(parametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(ar -> new MsalToken(ar, options)) .filter(t -> !t.isExpired()) .switchIfEmpty(Mono.fromFuture(() -> { SilentParameters.SilentParametersBuilder forceParametersBuilder = SilentParameters.builder( new HashSet<>(request.getScopes())).forceRefresh(true); if (account != null) { forceParametersBuilder = forceParametersBuilder.account(account); } try { return getPublicClientApplication(false).acquireTokenSilently(forceParametersBuilder.build()); } catch (MalformedURLException e) { throw logger.logExceptionAsError(Exceptions.propagate(e)); } }).map(result -> new MsalToken(result, options)))); } /** * Asynchronously acquire a token from Active Directory with a device code challenge. Active Directory will provide * a device code for login and the user must meet the challenge by authenticating in a browser on the current or a * different device. * * @param request the details of the token request * @param deviceCodeConsumer the user provided closure that will consume the device code challenge * @return a Publisher that emits an AccessToken when the device challenge is met, or an exception if the device * code expires */ public Mono<MsalToken> authenticateWithDeviceCode(TokenRequestContext request, Consumer<DeviceCodeInfo> deviceCodeConsumer) { return Mono.fromFuture(() -> { DeviceCodeFlowParameters parameters = DeviceCodeFlowParameters.builder(new HashSet<>(request.getScopes()), dc -> deviceCodeConsumer.accept(new DeviceCodeInfo(dc.userCode(), dc.deviceCode(), dc.verificationUri(), OffsetDateTime.now().plusSeconds(dc.expiresIn()), dc.message()))).build(); return getPublicClientApplication(false).acquireToken(parameters); }).onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with device code", null, t)) .map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory with Visual Sutdio cached refresh token. * * @param request the details of the token request * @return a Publisher that emits an AccessToken. */ public Mono<MsalToken> authenticateWithVsCodeCredential(TokenRequestContext request, String cloud) { VisualStudioCacheAccessor accessor = new VisualStudioCacheAccessor(); String credential = accessor.getCredentials("VS Code Azure", cloud); RefreshTokenParameters parameters = RefreshTokenParameters .builder(new HashSet<>(request.getScopes()), credential) .build(); return Mono.defer(() -> Mono.fromFuture(getPublicClientApplication(false).acquireToken(parameters)) .map(ar -> new MsalToken(ar, options))); } /** * Asynchronously acquire a token from Active Directory with an authorization code from an oauth flow. * * @param request the details of the token request * @param authorizationCode the oauth2 authorization code * @param redirectUrl the redirectUrl where the authorization code is sent to * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithAuthorizationCode(TokenRequestContext request, String authorizationCode, URI redirectUrl) { return Mono.fromFuture(() -> getPublicClientApplication(false).acquireToken( AuthorizationCodeParameters.builder(authorizationCode, redirectUrl) .scopes(new HashSet<>(request.getScopes())) .build())) .onErrorMap(t -> new ClientAuthenticationException("Failed to acquire token with authorization code", null, t)).map(ar -> new MsalToken(ar, options)); } /** * Asynchronously acquire a token from Active Directory by opening a browser and wait for the user to login. The * credential will run a minimal local HttpServer at the given port, so {@code http: * listed as a valid reply URL for the application. * * @param request the details of the token request * @param port the port on which the HTTP server is listening * @return a Publisher that emits an AccessToken */ public Mono<MsalToken> authenticateWithBrowserInteraction(TokenRequestContext request, int port) { String authorityUrl = options.getAuthorityHost().replaceAll("/+$", "") + "/" + tenantId; return AuthorizationCodeListener.create(port) .flatMap(server -> { URI redirectUri; String browserUri; try { redirectUri = new URI(String.format("http: browserUri = String.format("%s/oauth2/v2.0/authorize?response_type=code&response_mode=query&prompt" + "=select_account&client_id=%s&redirect_uri=%s&state=%s&scope=%s", authorityUrl, clientId, redirectUri.toString(), UUID.randomUUID(), String.join(" ", request.getScopes())); } catch (URISyntaxException e) { return server.dispose().then(Mono.error(e)); } return server.listen() .mergeWith(Mono.<String>fromRunnable(() -> { try { openUrl(browserUri); } catch (IOException e) { throw logger.logExceptionAsError(new IllegalStateException(e)); } }).subscribeOn(Schedulers.newSingle("browser"))) .next() .flatMap(code -> authenticateWithAuthorizationCode(request, code, redirectUri)) .onErrorResume(t -> server.dispose().then(Mono.error(t))) .flatMap(msalToken -> server.dispose().then(Mono.just(msalToken))); }); } /** * Gets token from shared token cache * */ public Mono<MsalToken> authenticateWithSharedTokenCache(TokenRequestContext request, String username) { return Mono.fromFuture(() -> getPublicClientApplication(true).getAccounts()) .onErrorMap(t -> new CredentialUnavailableException( "Cannot get accounts from token cache. Error: " + t.getMessage(), t)) .flatMap(set -> { IAccount requestedAccount; Map<String, IAccount> accounts = new HashMap<>(); if (set.isEmpty()) { return Mono.error(new CredentialUnavailableException("SharedTokenCacheCredential " + "authentication unavailable. No accounts were found in the cache.")); } for (IAccount cached : set) { if (username == null || username.equals(cached.username())) { if (!accounts.containsKey(cached.homeAccountId())) { accounts.put(cached.homeAccountId(), cached); } } } if (accounts.isEmpty()) { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. No account matching the specified username: %s was " + "found in the cache.", username))); } else if (accounts.size() > 1) { if (username == null) { return Mono.error(new RuntimeException("SharedTokenCacheCredential authentication " + "unavailable. Multiple accounts were found in the cache. Use username and " + "tenant id to disambiguate.")); } else { return Mono.error(new RuntimeException(String.format("SharedTokenCacheCredential " + "authentication unavailable. Multiple accounts matching the specified username: " + "%s were found in the cache.", username))); } } else { requestedAccount = accounts.values().iterator().next(); } return authenticateWithMsalAccount(request, requestedAccount); }); } /** * Asynchronously acquire a token from the App Service Managed Service Identity endpoint. * * @param msiEndpoint the endpoint to acquire token from * @param msiSecret the secret to acquire token with * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToManagedIdentityEndpoint(String msiEndpoint, String msiSecret, TokenRequestContext request) { return Mono.fromCallable(() -> { String resource = ScopeUtil.scopesToResource(request.getScopes()); HttpURLConnection connection = null; StringBuilder payload = new StringBuilder(); payload.append("resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); payload.append("&api-version="); payload.append(URLEncoder.encode("2017-09-01", "UTF-8")); if (clientId != null) { payload.append("&clientid="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } try { URL url = new URL(String.format("%s?%s", msiEndpoint, payload)); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); if (msiSecret != null) { connection.setRequestProperty("Secret", msiSecret); } connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } finally { if (connection != null) { connection.disconnect(); } } }); } /** * Asynchronously acquire a token from the Virtual Machine IMDS endpoint. * * @param request the details of the token request * @return a Publisher that emits an AccessToken */ public Mono<AccessToken> authenticateToIMDSEndpoint(TokenRequestContext request) { String resource = ScopeUtil.scopesToResource(request.getScopes()); StringBuilder payload = new StringBuilder(); final int imdsUpgradeTimeInMs = 70 * 1000; try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); payload.append("&resource="); payload.append(URLEncoder.encode(resource, "UTF-8")); if (clientId != null) { payload.append("&client_id="); payload.append(URLEncoder.encode(clientId, "UTF-8")); } } catch (IOException exception) { return Mono.error(exception); } return checkIMDSAvailable().flatMap(available -> Mono.fromCallable(() -> { int retry = 1; while (retry <= options.getMaxRetry()) { URL url = null; HttpURLConnection connection = null; try { url = new URL(String.format("http: payload.toString())); connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setRequestProperty("Metadata", "true"); connection.connect(); Scanner s = new Scanner(connection.getInputStream(), StandardCharsets.UTF_8.name()) .useDelimiter("\\A"); String result = s.hasNext() ? s.next() : ""; MSIToken msiToken = SERIALIZER_ADAPTER.deserialize(result, MSIToken.class, SerializerEncoding.JSON); return new IdentityToken(msiToken.getToken(), msiToken.getExpiresAt(), options); } catch (IOException exception) { if (connection == null) { throw logger.logExceptionAsError(new RuntimeException( String.format("Could not connect to the url: %s.", url), exception)); } int responseCode = connection.getResponseCode(); if (responseCode == 410 || responseCode == 429 || responseCode == 404 || (responseCode >= 500 && responseCode <= 599)) { int retryTimeoutInMs = options.getRetryTimeout() .apply(Duration.ofSeconds(RANDOM.nextInt(retry))).getNano() / 1000; retryTimeoutInMs = (responseCode == 410 && retryTimeoutInMs < imdsUpgradeTimeInMs) ? imdsUpgradeTimeInMs : retryTimeoutInMs; retry++; if (retry > options.getMaxRetry()) { break; } else { sleep(retryTimeoutInMs); } } else { throw logger.logExceptionAsError(new RuntimeException( "Couldn't acquire access token from IMDS, verify your objectId, " + "clientId or msiResourceId", exception)); } } finally { if (connection != null) { connection.disconnect(); } } } throw logger.logExceptionAsError(new RuntimeException( String.format("MSI: Failed to acquire tokens after retrying %s times", options.getMaxRetry()))); })); } private Mono<Boolean> checkIMDSAvailable() { StringBuilder payload = new StringBuilder(); try { payload.append("api-version="); payload.append(URLEncoder.encode("2018-02-01", "UTF-8")); } catch (IOException exception) { return Mono.error(exception); } return Mono.fromCallable(() -> { HttpURLConnection connection = null; URL url = new URL(String.format("http: payload.toString())); try { connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(500); connection.connect(); } catch (ConnectException | SecurityException | SocketTimeoutException e) { throw logger.logExceptionAsError( new CredentialUnavailableException("Connection to IMDS endpoint cannot be established. " + e.getMessage(), e)); } finally { if (connection != null) { connection.disconnect(); } } return true; }); } private static void sleep(int millis) { try { Thread.sleep(millis); } catch (InterruptedException ex) { throw new IllegalStateException(ex); } } private static Proxy proxyOptionsToJavaNetProxy(ProxyOptions options) { switch (options.getType()) { case SOCKS4: case SOCKS5: return new Proxy(Type.SOCKS, options.getAddress()); case HTTP: default: return new Proxy(Type.HTTP, options.getAddress()); } } private String getSafeWorkingDirectory() { if (isWindowsPlatform()) { if (CoreUtils.isNullOrEmpty(DEFAULT_WINDOWS_SYSTEM_ROOT)) { return null; } return DEFAULT_WINDOWS_SYSTEM_ROOT + "\\system32"; } else { return DEFAULT_MAC_LINUX_PATH; } } private boolean isWindowsPlatform() { return System.getProperty("os.name").contains("Windows"); } private String redactInfo(String regex, String input) { return input.replaceAll(regex, "****"); } void openUrl(String url) throws IOException { Runtime rt = Runtime.getRuntime(); String os = System.getProperty("os.name").toLowerCase(Locale.ROOT); if (os.contains("win")) { rt.exec("rundll32 url.dll,FileProtocolHandler " + url); } else if (os.contains("mac")) { rt.exec("open " + url); } else if (os.contains("nix") || os.contains("nux")) { rt.exec("xdg-open " + url); } else { logger.error("Browser could not be opened - please open {} in a browser on this device.", url); } } }
I assume this is better for perf since we don't allocate a new array every time?
public Mono<Void> runAsync() { return blobAsyncClient.download() .map(b -> { for (int i = 0; i < b.remaining(); i++) { b.get(); } return 1; }).then(); }
for (int i = 0; i < b.remaining(); i++) {
public Mono<Void> runAsync() { return blobAsyncClient.download() .map(b -> { for (int i = 0; i < b.remaining(); i++) { b.get(); } return 1; }).then(); }
class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
Should be better for perf since we don't create new flux every iteration.
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
Though is it safe to reuse the same flux for each iteration? Or is the flux "used up" after the first upload so we would need to create a new one every time?
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
yep, memory pressure is reduced.
public Mono<Void> runAsync() { return blobAsyncClient.download() .map(b -> { for (int i = 0; i < b.remaining(); i++) { b.get(); } return 1; }).then(); }
for (int i = 0; i < b.remaining(); i++) {
public Mono<Void> runAsync() { return blobAsyncClient.download() .map(b -> { for (int i = 0; i < b.remaining(); i++) { b.get(); } return 1; }).then(); }
class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
Yes, this reduces memory pressure as we don't really need to copy the data, just reading is sufficient.
public Mono<Void> runAsync() { return blobAsyncClient.download() .map(b -> { for (int i = 0; i < b.remaining(); i++) { b.get(); } return 1; }).then(); }
for (int i = 0; i < b.remaining(); i++) {
public Mono<Void> runAsync() { return blobAsyncClient.download() .map(b -> { for (int i = 0; i < b.remaining(); i++) { b.get(); } return 1; }).then(); }
class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
class NullOutputStream extends OutputStream { @Override public void write(int b) throws IOException { } }
Yeah, tested it by using the same flux to read multiple times. Same data was returned each time.
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
Would it also work with a static flux, if multiple instances were reading in parallel? Or does it need to be an instance flux, so it can be reused across iterations, but each instance needs its own copy? Shouldn't matter much for perf either way, but I like to scope variables correctly to increase understanding of the minimal test requirements.
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
It could have been static if the since of the buffer was fixed. Since the size is determined by the options provided in the constructor, I have made this an instance flux. However, as we discussed, we could make this static and initialize in `globalSetup()` as the options are not going to change for a run and all instances share the same option. I didn't want to make that assumption here as it didn't matter to the performance of the test itself.
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
return blobAsyncClient.upload(randomByteBufferFlux, null, true).then();
public Mono<Void> runAsync() { return blobAsyncClient.upload(randomByteBufferFlux, null, true).then(); }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
class UploadBlobTest extends BlobTestBase<PerfStressOptions> { private final Flux<ByteBuffer> randomByteBufferFlux; public UploadBlobTest(PerfStressOptions options) { super(options); this.randomByteBufferFlux = createRandomByteBufferFlux(options.getSize()); } @Override public void run() { throw new UnsupportedOperationException(); } @Override }
Could we use `!field.getValue().isNull()`?
public PatternAnalyzer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternAnalyzer analyzer = new PatternAnalyzer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { analyzer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { analyzer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); analyzer.setFlags(regexFlags); } else if ("lowercase".equals(field.getKey())){ analyzer.setLowerCaseTerms(field.getValue().asBoolean()); } else if ("stopwords".equals(field.getKey())) { List<String> stopWords = new ArrayList<>(); field.getValue().forEach( jsonNode -> stopWords.add(jsonNode.asText()) ); analyzer.setStopwords(stopWords); } } return analyzer; }
} else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) {
public PatternAnalyzer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternAnalyzer analyzer = new PatternAnalyzer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { analyzer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { analyzer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); analyzer.setFlags(regexFlags); } else if ("lowercase".equals(field.getKey())){ analyzer.setLowerCaseTerms(field.getValue().asBoolean()); } else if ("stopwords".equals(field.getKey())) { List<String> stopWords = new ArrayList<>(); field.getValue().forEach( jsonNode -> stopWords.add(jsonNode.asText()) ); analyzer.setStopwords(stopWords); } } return analyzer; }
class CustomPatternAnalyzerDeserializer extends JsonDeserializer<PatternAnalyzer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternAnalyzerDeserializer extends JsonDeserializer<PatternAnalyzer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
Do we have concern that `asInt` will return `int`'s default of 0 if the JSON value is `null`?
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
tokenizer.setGroup(field.getValue().asInt());
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
`!field.getValue().isNull()`
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
} else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) {
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
Don't know if the service would return this.
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
tokenizer.setGroup(field.getValue().asInt());
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
"null" is a string type in json
public PatternAnalyzer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternAnalyzer analyzer = new PatternAnalyzer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { analyzer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { analyzer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); analyzer.setFlags(regexFlags); } else if ("lowercase".equals(field.getKey())){ analyzer.setLowerCaseTerms(field.getValue().asBoolean()); } else if ("stopwords".equals(field.getKey())) { List<String> stopWords = new ArrayList<>(); field.getValue().forEach( jsonNode -> stopWords.add(jsonNode.asText()) ); analyzer.setStopwords(stopWords); } } return analyzer; }
} else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) {
public PatternAnalyzer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternAnalyzer analyzer = new PatternAnalyzer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { analyzer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { analyzer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); analyzer.setFlags(regexFlags); } else if ("lowercase".equals(field.getKey())){ analyzer.setLowerCaseTerms(field.getValue().asBoolean()); } else if ("stopwords".equals(field.getKey())) { List<String> stopWords = new ArrayList<>(); field.getValue().forEach( jsonNode -> stopWords.add(jsonNode.asText()) ); analyzer.setStopwords(stopWords); } } return analyzer; }
class CustomPatternAnalyzerDeserializer extends JsonDeserializer<PatternAnalyzer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternAnalyzerDeserializer extends JsonDeserializer<PatternAnalyzer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
It is a string type in json: `{"flags": "null"} ` what `field.getValue()`parse out here is "null". That's why I check it like this.
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
} else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) {
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
Based on the test of null group, service does not return group back if it is null.
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
tokenizer.setGroup(field.getValue().asInt());
public PatternTokenizer deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException { ObjectMapper mapper = new ObjectMapper(); ObjectNode root = mapper.readTree(p); Iterator<Map.Entry<String, JsonNode>> fields = root.fields(); PatternTokenizer tokenizer = new PatternTokenizer(); while (fields.hasNext()) { Map.Entry<String, JsonNode> field = fields.next(); if ("name".equals(field.getKey())) { tokenizer.setName(field.getValue().asText()); } else if ("pattern".equals(field.getKey())) { tokenizer.setPattern(field.getValue().asText()); } else if ("flags".equals(field.getKey()) && !"null".equals(field.getValue().asText())) { List<RegexFlags> regexFlags = Arrays.stream(field.getValue().asText().split(DELIMITER)) .map(RegexFlags::fromString).collect(Collectors.toList()); tokenizer.setFlags(regexFlags); } else if ("group".equals(field.getKey())){ tokenizer.setGroup(field.getValue().asInt()); } } return tokenizer; }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
class CustomPatternTokenizerDeserializer extends JsonDeserializer<PatternTokenizer> { private static final String DELIMITER = "\\|"; /** * {@inheritDoc} */ @Override }
Update : The service team intends to have additional keys added in between service updates. So to ensure this remains consistent the additional keys would be grouped into the `Map<String, FieldValue> extractedFields` [here]() and with proceeding client upgrades would be converted to strongly typed fields.
static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResult = analyzeResult.getDocumentResults(); List<ExtractedReceipt> extractedReceiptList = new ArrayList<>(); for (int i = 0; i < readResults.size(); i++) { ReadResult readResultItem = readResults.get(i); PageMetadata pageMetadata = getPageInfo(readResultItem); ExtractedReceipt extractedReceiptItem = new ExtractedReceipt(pageMetadata); DocumentResult documentResultItem = documentResult.get(i); documentResultItem.getFields().forEach((key, fieldValue) -> { switch (key) { case "ReceiptType": extractedReceiptItem.setReceiptType(new ReceiptType(fieldValue.getValueString(), fieldValue.getConfidence())); break; case "MerchantName": extractedReceiptItem.setMerchantName(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "MerchantAddress": extractedReceiptItem.setMerchantAddress(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "MerchantPhoneNumber": extractedReceiptItem.setMerchantPhoneNumber(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Subtotal": extractedReceiptItem.setSubtotal(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Tax": extractedReceiptItem.setTax(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Tip": extractedReceiptItem.setTip(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Total": extractedReceiptItem.setTotal(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "TransactionDate": extractedReceiptItem.setTransactionDate(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "TransactionTime": extractedReceiptItem.setTransactionTime(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Items": extractedReceiptItem.setReceiptItems(toReceiptItems(fieldValue.getValueArray(), readResults, includeTextDetails)); break; default: break; } }); extractedReceiptList.add(extractedReceiptItem); } return new IterableStream<>(extractedReceiptList); }
break;
static IterableStream<ExtractedReceipt> toReceipt(AnalyzeResult analyzeResult, boolean includeTextDetails) { List<ReadResult> readResults = analyzeResult.getReadResults(); List<DocumentResult> documentResult = analyzeResult.getDocumentResults(); List<ExtractedReceipt> extractedReceiptList = new ArrayList<>(); for (int i = 0; i < readResults.size(); i++) { ReadResult readResultItem = readResults.get(i); PageMetadata pageMetadata = getPageInfo(readResultItem); PageRange pageRange = null; DocumentResult documentResultItem = documentResult.get(i); List<Integer> receiptPageRange = documentResultItem.getPageRange(); if (receiptPageRange.size() == 2) { pageRange = new PageRange(receiptPageRange.get(0), receiptPageRange.get(1)); } ExtractedReceipt extractedReceiptItem = new ExtractedReceipt(pageMetadata, pageRange); Map<String, FieldValue<?>> extractedFieldMap = new HashMap<>(); documentResultItem.getFields().forEach((key, fieldValue) -> { switch (key) { case "ReceiptType": extractedReceiptItem.setReceiptType(new ReceiptType(fieldValue.getValueString(), fieldValue.getConfidence())); break; case "MerchantName": extractedReceiptItem.setMerchantName(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "MerchantAddress": extractedReceiptItem.setMerchantAddress(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "MerchantPhoneNumber": extractedReceiptItem.setMerchantPhoneNumber(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Subtotal": extractedReceiptItem.setSubtotal(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Tax": extractedReceiptItem.setTax(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Tip": extractedReceiptItem.setTip(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Total": extractedReceiptItem.setTotal(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "TransactionDate": extractedReceiptItem.setTransactionDate(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "TransactionTime": extractedReceiptItem.setTransactionTime(setFieldValue(fieldValue, readResults, includeTextDetails)); break; case "Items": extractedReceiptItem.setReceiptItems(toReceiptItems(fieldValue.getValueArray(), readResults, includeTextDetails)); break; default: extractedFieldMap.putIfAbsent(key, setFieldValue(fieldValue, readResults, includeTextDetails)); break; } }); extractedReceiptItem.setExtractedFields(extractedFieldMap); extractedReceiptList.add(extractedReceiptItem); } return new IterableStream<>(extractedReceiptList); }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern COMPILE = Pattern.compile("[^0-9]+"); private Transforms() { } private static FieldValue<?> setFieldValue(com.azure.ai.formrecognizer.implementation.models.FieldValue fieldValue, List<ReadResult> readResults, boolean includeTextDetails) { FieldValue<?> value; switch (fieldValue.getType()) { case PHONE_NUMBER: case STRING: case TIME: case DATE: value = toFieldValueString(fieldValue); break; case INTEGER: value = toFieldValueInteger(fieldValue); break; case NUMBER: value = toFieldValueNumber(fieldValue); break; case ARRAY: case OBJECT: default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } if (includeTextDetails) { value.setElements(setReferenceElements(readResults, fieldValue.getElements())); } return value; } private static PageMetadata getPageInfo(ReadResult readResultItem) { return new PageMetadata(TextLanguage.fromString(readResultItem.getLanguage().toString()), readResultItem.getHeight(), readResultItem.getPage(), readResultItem.getWidth(), readResultItem.getAngle(), DimensionUnit.fromString(readResultItem.getUnit().toString())); } private static List<Element> setReferenceElements(List<ReadResult> readResults, List<String> elements) { List<Element> elementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = COMPILE.matcher(elementString).replaceAll(" ").trim().split(" "); int readResultIndex, lineIndex; if (indices.length >= 1) { readResultIndex = Integer.parseInt(indices[0]); lineIndex = Integer.parseInt(indices[1]); } else { throw LOGGER.logExceptionAsError(new RuntimeException("Reference Elements not found")); } if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords() .get(wordIndex); WordElement wordElement = new WordElement(textWord.getText(), toBoundingBox(textWord.getBoundingBox())); elementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); LineElement lineElement = new LineElement(textLine.getText(), toBoundingBox(textLine.getBoundingBox())); elementList.add(lineElement); } }); return elementList; } private static BoundingBox toBoundingBox(List<Float> boundingBox) { List<Point> pointList = new ArrayList<>(); for (int i = 0; i < boundingBox.size(); i += 2) { Point point = new Point(boundingBox.get(i), boundingBox.get(i + 1)); pointList.add(point); } return new BoundingBox(pointList); } private static List<ReceiptItem> toReceiptItems( List<com.azure.ai.formrecognizer.implementation.models.FieldValue> fieldValue, List<ReadResult> readResults, boolean includeTextDetails) { List<ReceiptItem> receiptItemList = new ArrayList<>(); fieldValue.forEach(fieldValue1 -> { ReceiptItem receiptItem = new ReceiptItem(); fieldValue1.getValueObject().forEach((key, fieldValue2) -> { switch (key) { case "Quantity": receiptItem.setQuantity(setFieldValue(fieldValue2, readResults, includeTextDetails)); break; case "Name": receiptItem.setName(setFieldValue(fieldValue2, readResults, includeTextDetails)); break; case "TotalPrice": receiptItem.setTotalPrice(setFieldValue(fieldValue2, readResults, includeTextDetails)); break; default: break; } }); receiptItemList.add(receiptItem); }); return receiptItemList; } private static IntegerValue toFieldValueInteger(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceIntegerValue) { if (serviceIntegerValue.getValueNumber() != null) { return new IntegerValue(serviceIntegerValue.getText(), toBoundingBox(serviceIntegerValue.getBoundingBox()), serviceIntegerValue.getValueInteger()); } return new IntegerValue(serviceIntegerValue.getText(), toBoundingBox(serviceIntegerValue.getBoundingBox()), 0); } private static StringValue toFieldValueString(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceStringValue) { return new StringValue(serviceStringValue.getText(), toBoundingBox(serviceStringValue.getBoundingBox()), serviceStringValue.getValueString()); } private static FloatValue toFieldValueNumber(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceFloatValue) { return new FloatValue(serviceFloatValue.getText(), toBoundingBox(serviceFloatValue.getBoundingBox()), serviceFloatValue.getValueNumber()); } }
class Transforms { private static final ClientLogger LOGGER = new ClientLogger(Transforms.class); private static final Pattern COMPILE = Pattern.compile("[^0-9]+"); private Transforms() { } /** * Helper method to convert the {@link com.azure.ai.formrecognizer.implementation.models.AnalyzeOperationResult} * service level receipt model to list of {@link ExtractedReceipt}. * * @param analyzeResult The result of the analyze receipt operation returned by the service. * @param includeTextDetails When set to true, a list of references to the text elements is returned in the read result. * * @return A list of {@link ExtractedReceipt} to represent the list of extracted receipt information. */ /** * Helper method that converts the incoming service field value to one of the strongly typed SDK level {@link FieldValue} with * reference elements set when {@code includeTextDetails} is set to true. * * @param fieldValue The named field values returned by the service. * @param readResults The result containing the list of element references when includeTextDetails is set to true. * @param includeTextDetails When set to true, a list of references to the text elements is returned in the read result. * * @return The strongly typed {@link FieldValue} for the field input. */ private static FieldValue<?> setFieldValue(com.azure.ai.formrecognizer.implementation.models.FieldValue fieldValue, List<ReadResult> readResults, boolean includeTextDetails) { FieldValue<?> value; switch (fieldValue.getType()) { case PHONE_NUMBER: value = toFieldValuePhoneNumber(fieldValue); break; case STRING: value = toFieldValueString(fieldValue); break; case TIME: value = toFieldValueTime(fieldValue); break; case DATE: value = toFieldValueDate(fieldValue); break; case INTEGER: value = toFieldValueInteger(fieldValue); break; case NUMBER: value = toFieldValueNumber(fieldValue); break; case ARRAY: case OBJECT: default: throw LOGGER.logExceptionAsError(new RuntimeException("FieldValue Type not supported")); } if (includeTextDetails) { value.setElements(setReferenceElements(readResults, fieldValue.getElements())); } return value; } /** * Helper method that converts the service returned page information to SDK model {@link PageMetadata}. * * @param readResultItem A read result item returned from the service containing the page information for provided * input. * * @return The {@link PageMetadata} for the receipt page. */ private static PageMetadata getPageInfo(ReadResult readResultItem) { return new PageMetadata(readResultItem.getHeight(), readResultItem.getPage(), readResultItem.getWidth(), readResultItem.getAngle(), DimensionUnit.fromString(readResultItem.getUnit().toString())); } /** * Helper method to set the text reference elements on FieldValue/fields when {@code includeTextDetails} set to true. * * @param readResults The ReadResult containing the resolved references for text elements. * @param elements When includeTextDetails is set to true, a list of references to the text * elements constituting this field value. * * @return The updated {@link FieldValue} object with list if referenced elements. */ private static List<Element> setReferenceElements(List<ReadResult> readResults, List<String> elements) { List<Element> elementList = new ArrayList<>(); elements.forEach(elementString -> { String[] indices = COMPILE.matcher(elementString).replaceAll(" ").trim().split(" "); int readResultIndex, lineIndex; if (indices.length >= 1) { readResultIndex = Integer.parseInt(indices[0]); lineIndex = Integer.parseInt(indices[1]); } else { throw LOGGER.logExceptionAsError(new RuntimeException("Reference Elements not found")); } if (indices.length == 3) { int wordIndex = Integer.parseInt(indices[2]); TextWord textWord = readResults.get(readResultIndex).getLines().get(lineIndex).getWords() .get(wordIndex); WordElement wordElement = new WordElement(textWord.getText(), toBoundingBox(textWord.getBoundingBox())); elementList.add(wordElement); } else { TextLine textLine = readResults.get(readResultIndex).getLines().get(lineIndex); LineElement lineElement = new LineElement(textLine.getText(), toBoundingBox(textLine.getBoundingBox())); elementList.add(lineElement); } }); return elementList; } /** * Helper method to convert the service level modeled eight numbers representing the four points to SDK level * {@link BoundingBox}. * * @param boundingBox A list of eight numbers representing the four points of a box. * * @return A {@link BoundingBox}. */ private static BoundingBox toBoundingBox(List<Float> boundingBox) { BoundingBox boundingBox1; if (boundingBox.size() == 8) { Point topLeft = new Point(boundingBox.get(0), boundingBox.get(1)); Point topRight = new Point(boundingBox.get(2), boundingBox.get(3)); Point bottomLeft = new Point(boundingBox.get(4), boundingBox.get(5)); Point bottomRight = new Point(boundingBox.get(6), boundingBox.get(7)); boundingBox1 = new BoundingBox(topLeft, topRight, bottomLeft, bottomRight); } else { return null; } return boundingBox1; } /** * Helper method to convert the service level {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to SDK level {@link ReceiptItem receipt items}. * * @param fieldValueItems The named field values returned by the service. * @param readResults The result containing the list of element references when includeTextDetails is set to true. * @param includeTextDetails When set to true, a list of references to the text elements is returned in the read result. * * @return A list of {@link ReceiptItem}. */ private static List<ReceiptItem> toReceiptItems( List<com.azure.ai.formrecognizer.implementation.models.FieldValue> fieldValueItems, List<ReadResult> readResults, boolean includeTextDetails) { List<ReceiptItem> receiptItemList = new ArrayList<>(); for (com.azure.ai.formrecognizer.implementation.models.FieldValue eachFieldValue : fieldValueItems) { ReceiptItem receiptItem = new ReceiptItem(); for (ReceiptItemType key : ReceiptItemType.values()) { com.azure.ai.formrecognizer.implementation.models.FieldValue item = eachFieldValue.getValueObject().get(key.toString()); if (QUANTITY.equals(key) && item != null) { receiptItem.setQuantity(setFieldValue(item, readResults, includeTextDetails)); } else if (NAME.equals(key) && item != null) { receiptItem.setName(setFieldValue(item, readResults, includeTextDetails)); } else if (PRICE.equals(key) && item != null) { receiptItem.setPrice(setFieldValue(item, readResults, includeTextDetails)); } else if (TOTAL_PRICE.equals(key) && item != null) { receiptItem.setTotalPrice(setFieldValue(item, readResults, includeTextDetails)); } } receiptItemList.add(receiptItem); } return receiptItemList; } /** * Helper method to convert the service returned {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level {@link IntegerValue} * * @param serviceIntegerValue The integer value returned by the service in * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * * @return The {@link IntegerValue}. */ private static IntegerValue toFieldValueInteger(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceIntegerValue) { if (serviceIntegerValue.getValueNumber() != null) { return new IntegerValue(serviceIntegerValue.getText(), toBoundingBox(serviceIntegerValue.getBoundingBox()), serviceIntegerValue.getValueInteger(), serviceIntegerValue.getPage()); } return new IntegerValue(serviceIntegerValue.getText(), toBoundingBox(serviceIntegerValue.getBoundingBox()), null, serviceIntegerValue.getPage()); } /** * Helper method to convert the service returned {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level {@link StringValue}. * * @param serviceStringValue The string value returned by the service in * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * * @return The {@link StringValue}. */ private static StringValue toFieldValueString(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceStringValue) { return new StringValue(serviceStringValue.getText(), toBoundingBox(serviceStringValue.getBoundingBox()), serviceStringValue.getValueString(), serviceStringValue.getPage()); } /** * Helper method to convert the service returned {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level {@link FloatValue}. * * @param serviceFloatValue The float value returned by the service in * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * * @return The {@link FloatValue}. */ private static FloatValue toFieldValueNumber(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceFloatValue) { if (serviceFloatValue.getValueNumber() != null) { return new FloatValue(serviceFloatValue.getText(), toBoundingBox(serviceFloatValue.getBoundingBox()), serviceFloatValue.getValueNumber(), serviceFloatValue.getPage()); } return new FloatValue(serviceFloatValue.getText(), toBoundingBox(serviceFloatValue.getBoundingBox()), null, serviceFloatValue.getPage()); } /** * Helper method to convert the service returned {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level {@link StringValue}. * * @param serviceDateValue The string value returned by the service in * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * * @return The {@link StringValue}. */ private static StringValue toFieldValuePhoneNumber(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceDateValue) { return new StringValue(serviceDateValue.getText(), toBoundingBox(serviceDateValue.getBoundingBox()), serviceDateValue.getValuePhoneNumber(), serviceDateValue.getPage()); } /** * Helper method to convert the service returned {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level {@link DateValue}. * * @param serviceDateValue The string value returned by the service in * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * * @return The {@link StringValue}. */ private static DateValue toFieldValueDate(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceDateValue) { return new DateValue(serviceDateValue.getText(), toBoundingBox(serviceDateValue.getBoundingBox()), serviceDateValue.getValueDate(), serviceDateValue.getPage()); } /** * Helper method to convert the service returned {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * to a SDK level {@link TimeValue}. * * @param serviceDateValue The string value returned by the service in * {@link com.azure.ai.formrecognizer.implementation.models.FieldValue * * @return The {@link TimeValue}. * */ private static TimeValue toFieldValueTime(com.azure.ai.formrecognizer.implementation.models.FieldValue serviceDateValue) { return new TimeValue(serviceDateValue.getText(), toBoundingBox(serviceDateValue.getBoundingBox()), serviceDateValue.getValueTime(), serviceDateValue.getPage()); } }