Search in sources :

Example 31 with ServiceUnavailableException

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();
    }
}
Also used : Response(javax.ws.rs.core.Response) AuthResponse(uk.gov.pay.api.model.publicauth.AuthResponse) ErrorIdentifier(uk.gov.service.payments.commons.model.ErrorIdentifier) JsonNode(com.fasterxml.jackson.databind.JsonNode) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) AuthResponse(uk.gov.pay.api.model.publicauth.AuthResponse)

Example 32 with 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");
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) Test(org.junit.Test)

Example 33 with ServiceUnavailableException

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.");
    }
}
Also used : Invocation(javax.ws.rs.client.Invocation) EventInput(org.glassfish.jersey.media.sse.EventInput) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) Date(java.util.Date) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException)

Example 34 with ServiceUnavailableException

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;
}
Also used : EventOutput(org.glassfish.jersey.media.sse.EventOutput) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Example 35 with ServiceUnavailableException

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);
    }
}
Also used : ForbiddenException(javax.ws.rs.ForbiddenException) WebApplicationException(javax.ws.rs.WebApplicationException) NotAllowedException(javax.ws.rs.NotAllowedException) NotFoundException(javax.ws.rs.NotFoundException) NotAuthorizedException(javax.ws.rs.NotAuthorizedException) ServiceUnavailableException(javax.ws.rs.ServiceUnavailableException) Response(javax.ws.rs.core.Response) NotAcceptableException(javax.ws.rs.NotAcceptableException) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) ClientResponseProcessingException(org.glassfish.jersey.client.internal.ClientResponseProcessingException) ResponseProcessingException(javax.ws.rs.client.ResponseProcessingException) NotSupportedException(javax.ws.rs.NotSupportedException)

Aggregations

ServiceUnavailableException (javax.ws.rs.ServiceUnavailableException)40 NotFoundException (javax.ws.rs.NotFoundException)16 GET (javax.ws.rs.GET)13 Path (javax.ws.rs.Path)13 Produces (javax.ws.rs.Produces)13 WebApplicationException (javax.ws.rs.WebApplicationException)13 BadRequestException (javax.ws.rs.BadRequestException)12 Response (javax.ws.rs.core.Response)12 ForbiddenException (javax.ws.rs.ForbiddenException)9 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)8 DataFile (edu.harvard.iq.dataverse.DataFile)7 ByteArrayOutputStream (java.io.ByteArrayOutputStream)7 IOException (java.io.IOException)7 ClientErrorException (javax.ws.rs.ClientErrorException)7 ServerErrorException (javax.ws.rs.ServerErrorException)7 Test (org.junit.Test)6 NotAuthorizedException (javax.ws.rs.NotAuthorizedException)4 RedirectionException (javax.ws.rs.RedirectionException)4 CircuitBreakerConfiguration (com.oracle.bmc.circuitbreaker.CircuitBreakerConfiguration)3 FileMetadata (edu.harvard.iq.dataverse.FileMetadata)3