下面列出了怎么用javax.naming.ServiceUnavailableException的API类实例代码及写法,或者点击链接到github查看源代码。
private AuthenticationResult acquireAccessTokenUsingDeviceCodeFlow() throws Exception {
AuthenticationContext context = null;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
context = new AuthenticationContext(aadAuthorityUri, true, service);
Future<DeviceCode> future = context.acquireDeviceCode(CLIENT_ID, clusterUrl, null);
DeviceCode deviceCode = future.get();
System.out.println(deviceCode.getMessage());
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(new URI(deviceCode.getVerificationUrl()));
}
result = waitAndAcquireTokenByDeviceCode(deviceCode, context);
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
}
return result;
}
AuthenticationResult acquireWithClientCertificate()
throws InterruptedException, ExecutionException, ServiceUnavailableException {
AuthenticationContext context;
AuthenticationResult result = null;
ExecutorService service = null;
try {
service = Executors.newSingleThreadExecutor();
context = new AuthenticationContext(aadAuthorityUri, false, service);
AsymmetricKeyCredential asymmetricKeyCredential = AsymmetricKeyCredential.create(applicationClientId,
privateKey, x509Certificate);
// pass null value for optional callback function and acquire access token
result = context.acquireToken(clusterUrl, asymmetricKeyCredential, null).get();
} catch (MalformedURLException e) {
e.printStackTrace();
} finally {
if (service != null) {
service.shutdown();
}
}
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
}
return result;
}
@Test
public void testRetryOnThrowableCondition() throws Exception {
Func1<Observable<? extends Throwable>, Observable<?>> retryFun = builder
.withRetryOnThrowable(ex -> ex instanceof ServiceUnavailableException)
.buildExponentialBackoff();
observableOf("A", new ServiceUnavailableException("Retry me"), "B", new IllegalArgumentException("Do not retry"), "C")
.retryWhen(retryFun, testScheduler)
.subscribe(testSubscriber);
// Expect first item
testScheduler.triggerActions();
assertThat(testSubscriber.getLatestItem()).isEqualTo("A");
// Expect second item
testScheduler.advanceTimeBy(RETRY_DELAY_SEC, TimeUnit.SECONDS);
assertThat(testSubscriber.getLatestItem()).isEqualTo("B");
// Expect third item
testScheduler.advanceTimeBy(2 * RETRY_DELAY_SEC, TimeUnit.SECONDS);
testSubscriber.assertOnError(IOException.class);
assertThat(testSubscriber.isUnsubscribed());
}
IAuthenticationResult getAuthResultBySilentFlow(HttpServletRequest httpRequest, String scope) throws Throwable {
IAuthenticationResult result = AuthHelper.getAuthSessionObject(httpRequest);
IAuthenticationResult updatedResult;
ConfidentialClientApplication app;
try {
app = createClientApplication();
Object tokenCache = httpRequest.getSession().getAttribute("token_cache");
if(tokenCache != null){
app.tokenCache().deserialize(tokenCache.toString());
}
SilentParameters parameters = SilentParameters.builder(
Collections.singleton(scope),
result.account()).build();
CompletableFuture<IAuthenticationResult> future = app.acquireTokenSilently(parameters);
updatedResult = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
if (updatedResult == null) {
throw new ServiceUnavailableException("authentication result was null");
}
//update session with latest token cache
storeTokenCacheInSession(httpRequest, app.tokenCache().serialize());
return updatedResult;
}
IAuthenticationResult getAuthResultByAuthCode(
HttpServletRequest httpServletRequest,
AuthorizationCode authorizationCode,
String currentUri, Set<String> scopes) throws Throwable {
IAuthenticationResult result;
ConfidentialClientApplication app;
try {
app = createClientApplication();
String authCode = authorizationCode.getValue();
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(
authCode,
new URI(currentUri))
.scopes(scopes)
.build();
Future<IAuthenticationResult> future = app.acquireToken(parameters);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
}
storeTokenCacheInSession(httpServletRequest, app.tokenCache().serialize());
return result;
}
private IAuthenticationResult getAuthResultByAuthCode(
HttpServletRequest httpServletRequest,
AuthorizationCode authorizationCode,
String currentUri) throws Throwable {
IAuthenticationResult result;
ConfidentialClientApplication app;
try {
app = createClientApplication();
String authCode = authorizationCode.getValue();
AuthorizationCodeParameters parameters = AuthorizationCodeParameters.builder(
authCode,
new URI(currentUri)).
build();
Future<IAuthenticationResult> future = app.acquireToken(parameters);
result = future.get();
} catch (ExecutionException e) {
throw e.getCause();
}
if (result == null) {
throw new ServiceUnavailableException("authentication result was null");
}
SessionManagementHelper.storeTokenCacheInSession(httpServletRequest, app.tokenCache().serialize());
return result;
}
@Test
@DisplayName("validate cached token. Refresh if needed. Call regularly if no refresh token")
void useCachedTokenAndRefreshWhenNeeded() throws InterruptedException, ExecutionException, ServiceUnavailableException, IOException, DataServiceException, URISyntaxException, CertificateException, OperatorCreationException, PKCSException {
String certFilePath = Paths.get("src", "test", "resources", "cert.cer").toString();
String privateKeyPath = Paths.get("src", "test", "resources", "key.pem").toString();
X509Certificate x509Certificate = readPem(certFilePath, "basic").getCertificate();
PrivateKey privateKey = readPem(privateKeyPath, "basic").getKey();
ConnectionStringBuilder csb = ConnectionStringBuilder
.createWithAadApplicationCertificate("resource.uri", "client-id", x509Certificate, privateKey);
AadAuthenticationHelper aadAuthenticationHelperSpy = spy(new AadAuthenticationHelper(csb));
AuthenticationResult authenticationResult = new AuthenticationResult("testType", "firstToken", "refreshToken", 0, "id", mock(UserInfo.class), false);
AuthenticationResult authenticationResultFromRefresh = new AuthenticationResult("testType", "fromRefresh", null, 90, "id", mock(UserInfo.class), false);
AuthenticationResult authenticationResultNullRefreshTokenResult = new AuthenticationResult("testType", "nullRefreshResult", null, 0, "id", mock(UserInfo.class), false);
doReturn(authenticationResultFromRefresh).when(aadAuthenticationHelperSpy).acquireAccessTokenByRefreshToken();
doReturn(authenticationResult).when(aadAuthenticationHelperSpy).acquireWithClientCertificate();
assertEquals("firstToken", aadAuthenticationHelperSpy.acquireAccessToken());
// Token was passed as expired - expected to be refreshed
assertEquals("fromRefresh", aadAuthenticationHelperSpy.acquireAccessToken());
// Token is still valid - expected to return the same
assertEquals("fromRefresh", aadAuthenticationHelperSpy.acquireAccessToken());
doReturn(new Date(System.currentTimeMillis() + MIN_ACCESS_TOKEN_VALIDITY_IN_MILLISECS * 2)).when(aadAuthenticationHelperSpy).dateInAMinute();
doReturn(authenticationResultNullRefreshTokenResult).when(aadAuthenticationHelperSpy).acquireWithClientCertificate();
// Null refresh token + token is now expired- expected to authenticate again and reacquire token
assertEquals("nullRefreshResult", aadAuthenticationHelperSpy.acquireAccessToken());
}
/**
* Builds an {@link AuthenticationInfo} object by querying the active directory LDAP context for the
* specified username.
*/
@Nullable
@Override
protected AuthenticationInfo queryForAuthenticationInfo(
AuthenticationToken token, LdapContextFactory ldapContextFactory) throws NamingException {
try {
return queryForAuthenticationInfo0(token, ldapContextFactory);
} catch (ServiceUnavailableException e) {
// It might be a temporary failure, so try again.
return queryForAuthenticationInfo0(token, ldapContextFactory);
}
}
@Test
public void testRetryOnThrowable() {
StepVerifier
.withVirtualTime(() ->
streamOf("A", new ServiceUnavailableException("Retry me"), "B", new IllegalArgumentException("Do not retry me."), "C")
.retryWhen(newRetryHandlerBuilder().withRetryOnThrowable(ex -> ex instanceof ServiceUnavailableException).buildReactorExponentialBackoff())
)
.expectNext("A")
.expectNoEvent(Duration.ofSeconds(RETRY_DELAY_SEC))
.expectNext("B")
.expectErrorMatches(e -> e instanceof IOException && e.getCause() instanceof IllegalArgumentException)
.verify();
}
public boolean errorIsRetryable( final Exception e )
{
if ( e instanceof CommunicationException || e instanceof ServiceUnavailableException )
{
final String msgText = e.getMessage();
if ( msgText != null && !msgText.toLowerCase().contains( "unrecognized extended operation" ) )
{
return true;
}
}
return super.errorIsRetryable( e );
}
/**
* This tests to validate the RegionServer's ConnectorServer after unauthorised stopRegionServer
* call.
*/
@Test
public void testRSConnectorServerWhenStopRegionServer() throws Exception {
conf.set(CoprocessorHost.REGIONSERVER_COPROCESSOR_CONF_KEY,
JMXListener.class.getName() + "," + MyAccessController.class.getName());
conf.setInt("regionserver.rmi.registry.port", rmiRegistryPort);
UTIL.startMiniCluster();
admin = UTIL.getConnection().getAdmin();
hasAccess = false;
ServerName serverName = UTIL.getHBaseCluster().getRegionServer(0).getServerName();
LOG.info("Stopping Region Server...");
admin.stopRegionServer(serverName.getHostname() + ":" + serverName.getPort());
// Check whether Region Sever JMX Connector server can be connected
JMXConnector connector = null;
try {
connector = JMXConnectorFactory
.connect(JMXListener.buildJMXServiceURL(rmiRegistryPort, rmiRegistryPort));
} catch (IOException e) {
if (e.getCause() instanceof ServiceUnavailableException) {
Assert.fail("Can't connect to Region Server ConnectorServer.");
}
}
Assert.assertNotNull("JMXConnector should not be null.", connector);
connector.close();
}
@GetMapping("/discoveryClient")
public String discoveryPing() throws RestClientException, ServiceUnavailableException {
URI service = serviceUrl().map(s -> s.resolve("/ping"))
.orElseThrow(ServiceUnavailableException::new);
return restTemplate.getForEntity(service, String.class)
.getBody();
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
/**
* Reads a reply; waits until one is ready.
*/
BerDecoder readReply(LdapRequest ldr)
throws IOException, NamingException {
BerDecoder rber;
boolean waited = false;
while (((rber = ldr.getReplyBer()) == null) && !waited) {
try {
// If socket closed, don't even try
synchronized (this) {
if (sock == null) {
throw new ServiceUnavailableException(host + ":" + port +
"; socket closed");
}
}
synchronized (ldr) {
// check if condition has changed since our last check
rber = ldr.getReplyBer();
if (rber == null) {
if (readTimeout > 0) { // Socket read timeout is specified
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
ldr.wait(15 * 1000); // 15 second timeout
}
} else {
break;
}
}
} catch (InterruptedException ex) {
throw new InterruptedNamingException(
"Interrupted during LDAP operation");
}
}
if ((rber == null) && waited) {
removeRequest(ldr);
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
}
return rber;
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
/**
* Reads a reply; waits until one is ready.
*/
BerDecoder readReply(LdapRequest ldr)
throws IOException, NamingException {
BerDecoder rber;
boolean waited = false;
while (((rber = ldr.getReplyBer()) == null) && !waited) {
try {
// If socket closed, don't even try
synchronized (this) {
if (sock == null) {
throw new ServiceUnavailableException(host + ":" + port +
"; socket closed");
}
}
synchronized (ldr) {
// check if condition has changed since our last check
rber = ldr.getReplyBer();
if (rber == null) {
if (readTimeout > 0) { // Socket read timeout is specified
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
ldr.wait(15 * 1000); // 15 second timeout
}
} else {
break;
}
}
} catch (InterruptedException ex) {
throw new InterruptedNamingException(
"Interrupted during LDAP operation");
}
}
if ((rber == null) && waited) {
removeRequest(ldr);
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
}
return rber;
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
/**
* Reads a reply; waits until one is ready.
*/
BerDecoder readReply(LdapRequest ldr)
throws IOException, NamingException {
BerDecoder rber;
boolean waited = false;
while (((rber = ldr.getReplyBer()) == null) && !waited) {
try {
// If socket closed, don't even try
synchronized (this) {
if (sock == null) {
throw new ServiceUnavailableException(host + ":" + port +
"; socket closed");
}
}
synchronized (ldr) {
// check if condition has changed since our last check
rber = ldr.getReplyBer();
if (rber == null) {
if (readTimeout > 0) { // Socket read timeout is specified
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
// no timeout is set so we wait infinitely until
// a response is received
// https://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
ldr.wait();
}
} else {
break;
}
}
} catch (InterruptedException ex) {
throw new InterruptedNamingException(
"Interrupted during LDAP operation");
}
}
if ((rber == null) && waited) {
abandonRequest(ldr, null);
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
}
return rber;
}
@Override
public boolean isCausedByNetworkIssue(CertStoreException e) {
Throwable t = e.getCause();
return (t != null && (t instanceof ServiceUnavailableException ||
t instanceof CommunicationException));
}
/**
* Reads a reply; waits until one is ready.
*/
BerDecoder readReply(LdapRequest ldr)
throws IOException, NamingException {
BerDecoder rber;
boolean waited = false;
while (((rber = ldr.getReplyBer()) == null) && !waited) {
try {
// If socket closed, don't even try
synchronized (this) {
if (sock == null) {
throw new ServiceUnavailableException(host + ":" + port +
"; socket closed");
}
}
synchronized (ldr) {
// check if condition has changed since our last check
rber = ldr.getReplyBer();
if (rber == null) {
if (readTimeout > 0) { // Socket read timeout is specified
// will be woken up before readTimeout only if reply is
// available
ldr.wait(readTimeout);
waited = true;
} else {
// no timeout is set so we wait infinitely until
// a response is received
// https://docs.oracle.com/javase/8/docs/technotes/guides/jndi/jndi-ldap.html#PROP
ldr.wait();
}
} else {
break;
}
}
} catch (InterruptedException ex) {
throw new InterruptedNamingException(
"Interrupted during LDAP operation");
}
}
if ((rber == null) && waited) {
abandonRequest(ldr, null);
throw new NamingException("LDAP response read timed out, timeout used:"
+ readTimeout + "ms." );
}
return rber;
}
public ElastiCenterClient(String address, String key) throws InvalidCredentialsException, InvalidParameterException, SSLHandshakeException, ServiceUnavailableException {
elastiCenterAddress = address;
apiKey = key;
initialize();
}
public Object executeCommand(String command, MultivaluedMap<String, String> params, Object responeObj) throws Throwable {
if (!initialized) {
throw new IllegalStateException("Error : ElastiCenterClient is not initialized.");
}
if (command == null || command.trim().isEmpty()) {
throw new InvalidParameterException("No command to execute.");
}
try {
ClientConfig config = new DefaultClientConfig();
Client client = Client.create(config);
WebResource webResource = client.resource(UriBuilder.fromUri(restprotocol + elastiCenterAddress + restpath).build());
MultivaluedMap<String, String> queryParams = new MultivaluedMapImpl();
queryParams.add(queryparamapikey, apiKey);
queryParams.add(queryparamresponse, responseType);
queryParams.add(queryparamcommand, command);
if (null != params) {
for (String key : params.keySet()) {
queryParams.add(key, params.getFirst(key));
}
}
if (debug) {
System.out.println("Command Sent " + command + " : " + queryParams);
}
ClientResponse response = webResource.queryParams(queryParams).accept(MediaType.APPLICATION_JSON).get(ClientResponse.class);
if (response.getStatus() >= 300) {
if (debug)
System.out.println("ElastiCenter returned error code : " + response.getStatus());
if (401 == response.getStatus()) {
throw new InvalidCredentialsException("Please specify a valid API Key.");
} else if (431 == response.getStatus()) {
throw new InvalidParameterException(response.getHeaders().getFirst("X-Description"));
} else if (432 == response.getStatus()) {
throw new InvalidParameterException(command + " does not exist on the ElastiCenter server. Please specify a valid command or contact your ElastiCenter Administrator.");
} else {
throw new ServiceUnavailableException("Internal Error. Please contact your ElastiCenter Administrator.");
}
} else if (null != responeObj) {
String jsonResponse = response.getEntity(String.class);
if (debug) {
System.out.println("Command Response : " + jsonResponse);
}
Gson gson = new Gson();
return gson.fromJson(jsonResponse, responeObj.getClass());
} else {
return "Success";
}
} catch (Throwable t) {
throw t;
}
}