use of javax.ws.rs.ServiceUnavailableException in project pay-publicapi by alphagov.
the class AccountAuthenticator method authenticate.
@Override
public Optional<Account> authenticate(String bearerToken) {
Response response = client.target(publicAuthUrl).request().header(AUTHORIZATION, "Bearer " + bearerToken).accept(MediaType.APPLICATION_JSON).get();
if (response.getStatus() == OK.getStatusCode()) {
AuthResponse authResponse = response.readEntity(AuthResponse.class);
logger.info(format("Successfully authenticated using API key with token_link %s", authResponse.getTokenLink()), kv("token_link", authResponse.getTokenLink()));
return Optional.of(new Account(authResponse.getAccountId(), authResponse.getTokenType(), authResponse.getTokenLink()));
} else if (response.getStatus() == UNAUTHORIZED.getStatusCode()) {
JsonNode unauthorisedResponse = response.readEntity(JsonNode.class);
ErrorIdentifier errorIdentifier = ErrorIdentifier.valueOf(unauthorisedResponse.get("error_identifier").asText());
if (errorIdentifier == ErrorIdentifier.AUTH_TOKEN_REVOKED) {
String tokenLink = unauthorisedResponse.get("token_link").asText();
logger.warn(format("Attempt to authenticate using revoked API key with token_link %s", tokenLink), kv("token_link", tokenLink));
} else {
logger.warn("Attempt to authenticate using invalid API key with valid checksum");
}
response.close();
return Optional.empty();
} else {
response.close();
logger.warn("Unexpected status code " + response.getStatus() + " from auth.");
throw new ServiceUnavailableException();
}
}
use of javax.ws.rs.ServiceUnavailableException in project conjure-java-runtime by palantir.
the class WebApplicationExceptionMapperTest method testNotExplicitlyHandledExceptions.
@Test
public void testNotExplicitlyHandledExceptions() throws Exception {
Response response;
response = mapper.toResponse(new WebApplicationException("secret", 503));
String entity = objectMapper.writeValueAsString(response.getEntity());
assertThat(entity).contains("\"errorCode\" : \"javax.ws.rs.WebApplicationException\"");
assertThat(entity).contains("\"errorName\" : \"WebApplicationException\"");
assertThat(response.getStatus()).isEqualTo(503);
assertThat(entity).doesNotContain("secret");
response = mapper.toResponse(new ServiceUnavailableException("secret"));
entity = objectMapper.writeValueAsString(response.getEntity());
assertThat(entity).contains("\"errorCode\" : \"javax.ws.rs.ServiceUnavailableException\"");
assertThat(entity).contains("\"errorName\" : \"ServiceUnavailableException\"");
assertThat(response.getStatus()).isEqualTo(503);
assertThat(entity).doesNotContain("secret");
}
use of javax.ws.rs.ServiceUnavailableException in project jersey by eclipse-ee4j.
the class EventProcessor method run.
@Override
public void run() {
LOGGER.debugLog("Listener task started.");
EventInput eventInput = null;
try {
try {
final Invocation.Builder request = prepareHandshakeRequest();
if (state.get() == State.OPEN) {
// attempt to connect only if even source is open
LOGGER.debugLog("Connecting...");
eventInput = request.get(EventInput.class);
LOGGER.debugLog("Connected!");
}
} finally {
if (firstContactSignal != null) {
// release the signal regardless of event source state or connection request outcome
firstContactSignal.countDown();
}
}
final Thread execThread = Thread.currentThread();
while (state.get() == State.OPEN && !execThread.isInterrupted()) {
if (eventInput == null || eventInput.isClosed()) {
LOGGER.debugLog("Connection lost - scheduling reconnect in {0} ms", reconnectDelay);
scheduleReconnect(reconnectDelay);
break;
} else {
this.onEvent(eventInput.read());
}
}
} catch (ServiceUnavailableException ex) {
LOGGER.debugLog("Received HTTP 503");
long delay = reconnectDelay;
if (ex.hasRetryAfter()) {
LOGGER.debugLog("Recovering from HTTP 503 using HTTP Retry-After header value as a reconnect delay");
final Date requestTime = new Date();
delay = ex.getRetryTime(requestTime).getTime() - requestTime.getTime();
delay = (delay > 0) ? delay : 0;
}
LOGGER.debugLog("Recovering from HTTP 503 - scheduling to reconnect in {0} ms", delay);
scheduleReconnect(delay);
} catch (Exception ex) {
if (LOGGER.isLoggable(CONNECTION_ERROR_LEVEL)) {
LOGGER.log(CONNECTION_ERROR_LEVEL, String.format("Unable to connect - closing the event source to %s.", target.getUri().toASCIIString()), ex);
}
// if we're here, an unrecoverable error has occurred - just turn off the lights...
shutdownHandler.shutdown();
} finally {
if (eventInput != null && !eventInput.isClosed()) {
eventInput.close();
}
LOGGER.debugLog("Listener task finished.");
}
}
use of javax.ws.rs.ServiceUnavailableException in project jersey by eclipse-ee4j.
the class ItemStoreResource method itemEvents.
/**
* Connect or re-connect to SSE event stream.
*
* @param lastEventId Value of custom SSE HTTP <tt>{@value SseFeature#LAST_EVENT_ID_HEADER}</tt> header.
* Defaults to {@code -1} if not set.
* @return new SSE event output stream representing the (re-)established SSE client connection.
* @throws InternalServerErrorException in case replaying missed events to the reconnected output stream fails.
* @throws ServiceUnavailableException in case the reconnect delay is set to a positive value.
*/
@GET
@Path("events")
@Produces(SseFeature.SERVER_SENT_EVENTS)
public EventOutput itemEvents(@HeaderParam(SseFeature.LAST_EVENT_ID_HEADER) @DefaultValue("-1") int lastEventId) {
final EventOutput eventOutput = new EventOutput();
if (lastEventId >= 0) {
LOGGER.info("Received last event id :" + lastEventId);
// decide the reconnect handling strategy based on current reconnect delay value.
final long delay = reconnectDelay;
if (delay > 0) {
LOGGER.info("Non-zero reconnect delay [" + delay + "] - responding with HTTP 503.");
throw new ServiceUnavailableException(delay);
} else {
LOGGER.info("Zero reconnect delay - reconnecting.");
replayMissedEvents(lastEventId, eventOutput);
}
}
if (!broadcaster.add(eventOutput)) {
LOGGER.severe("!!! Unable to add new event output to the broadcaster !!!");
// let's try to force a 5s delayed client reconnect attempt
throw new ServiceUnavailableException(5L);
}
return eventOutput;
}
use of javax.ws.rs.ServiceUnavailableException in project jersey by eclipse-ee4j.
the class JerseyInvocation method convertToException.
private ProcessingException convertToException(final Response response) {
// Use an empty response if ignoring response in exception
final int statusCode = response.getStatus();
final Response finalResponse = ignoreResponseException ? Response.status(statusCode).build() : response;
try {
// Buffer and close entity input stream (if any) to prevent
// leaking connections (see JERSEY-2157).
response.bufferEntity();
final WebApplicationException webAppException;
final Response.Status status = Response.Status.fromStatusCode(statusCode);
if (status == null) {
final Response.Status.Family statusFamily = finalResponse.getStatusInfo().getFamily();
webAppException = createExceptionForFamily(finalResponse, statusFamily);
} else {
switch(status) {
case BAD_REQUEST:
webAppException = new BadRequestException(finalResponse);
break;
case UNAUTHORIZED:
webAppException = new NotAuthorizedException(finalResponse);
break;
case FORBIDDEN:
webAppException = new ForbiddenException(finalResponse);
break;
case NOT_FOUND:
webAppException = new NotFoundException(finalResponse);
break;
case METHOD_NOT_ALLOWED:
webAppException = new NotAllowedException(finalResponse);
break;
case NOT_ACCEPTABLE:
webAppException = new NotAcceptableException(finalResponse);
break;
case UNSUPPORTED_MEDIA_TYPE:
webAppException = new NotSupportedException(finalResponse);
break;
case INTERNAL_SERVER_ERROR:
webAppException = new InternalServerErrorException(finalResponse);
break;
case SERVICE_UNAVAILABLE:
webAppException = new ServiceUnavailableException(finalResponse);
break;
default:
final Response.Status.Family statusFamily = finalResponse.getStatusInfo().getFamily();
webAppException = createExceptionForFamily(finalResponse, statusFamily);
}
}
return new ResponseProcessingException(finalResponse, webAppException);
} catch (final Throwable t) {
return new ResponseProcessingException(finalResponse, LocalizationMessages.RESPONSE_TO_EXCEPTION_CONVERSION_FAILED(), t);
}
}
Aggregations