Java Code Examples for javax.ws.rs.WebApplicationException#getResponse()

The following examples show how to use javax.ws.rs.WebApplicationException#getResponse() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: WebApplicationExceptionHandler.java    From govpay with GNU General Public License v3.0 6 votes vote down vote up
@Override
public Response toResponse(WebApplicationException e) 
{ 
	if(this.excludeFaultBean) {
		ResponseBuilder responseBuilder = Response.status(e.getResponse().getStatus());
		if(e.getResponse().getHeaders()!=null) {
			MultivaluedMap<String, Object> map = e.getResponse().getHeaders();
			if(!map.isEmpty()) {
				map.keySet().stream().forEach(k -> {
					responseBuilder.header(k, map.get(k));
				});
			}
		}
		return responseBuilder.build();
	} else {
		return e.getResponse();
	}

}
 
Example 2
Source File: DefaultExceptionMapperTest.java    From microprofile-rest-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testPropagationOfResponseDetailsFromDefaultMapper() throws Exception {
    stubFor(get(urlEqualTo("/")).willReturn(aResponse().withStatus(STATUS).withBody(BODY)));

    SimpleGetApi simpleGetApi = RestClientBuilder.newBuilder()
        .baseUri(getServerURI())
        .build(SimpleGetApi.class);

    try {
        simpleGetApi.executeGet();
        fail("A "+WebApplicationException.class+" should have been thrown automatically");
    }
    catch (WebApplicationException w) {
        Response response = w.getResponse();
        // the response should have the response code from the api call
        assertEquals(response.getStatus(), STATUS,
            "The 401 from the response should be propagated");
        String body = response.readEntity(String.class);
        assertEquals(body, BODY,
            "The body of the response should be propagated");
        response.close();
    }
}
 
Example 3
Source File: ProxyServlet.java    From openwebbeans-meecrowave with Apache License 2.0 6 votes vote down vote up
protected Void onError(final Routes.Route route,
                       final HttpServletRequest request, final HttpServletResponse resp,
                       final Throwable error) {
    try {
        if (WebApplicationException.class.isInstance(error)) {
            final WebApplicationException wae = WebApplicationException.class.cast(error);
            if (wae.getResponse() != null) {
                forwardResponse(route, wae.getResponse(), request, resp, identity());
                return null;
            }
        }
        onDefaultError(resp, error);
    } catch (final IOException ioe) {
        getServletContext().log(ioe.getMessage(), ioe);
        throw new IllegalStateException(ioe);
    }
    return null;
}
 
Example 4
Source File: AuthorizationUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowAuthorizationFailureSingleChallenge() {
    try {
        AuthorizationUtils.throwAuthorizationFailure(Collections.singleton("Basic"));
        fail("WebApplicationException expected");
    } catch (WebApplicationException ex) {
        Response r = ex.getResponse();
        assertEquals(401, r.getStatus());
        Object value = r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
        assertNotNull(value);
        assertEquals("Basic", value.toString());
    }
}
 
Example 5
Source File: WebApplicationExceptionMapper.java    From openscoring with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception){
	Response response = exception.getResponse();

	Throwable throwable = exception;

	Map<Throwable, Throwable> throwableMap = new IdentityHashMap<>();

	while(true){
		Throwable cause = throwable.getCause();
		throwableMap.put(throwable, cause);

		if((cause == null) || throwableMap.containsKey(cause)){
			break;
		}

		throwable = cause;
	}

	String message = throwable.getMessage();
	if((message == null) || ("").equals(message)){
		Response.Status status = (Response.Status)response.getStatusInfo();

		message = status.getReasonPhrase();
	} // End if

	// Strip the HTTP status code prefix
	if(message.startsWith("HTTP ")){
		message = message.replaceFirst("^HTTP (\\d)+ ", "");
	}

	SimpleResponse entity = new SimpleResponse();
	entity.setMessage(message);

	return (Response.fromResponse(response).entity(entity).type(MediaType.APPLICATION_JSON)).build();
}
 
Example 6
Source File: RateLimiterFilterTest.java    From pay-publicapi with MIT License 5 votes vote down vote up
@Test
public void shouldSendErrorResponse_whenRateLimitExceeded() throws Exception {
    doThrow(RateLimitException.class).when(rateLimiter).checkRateOf(eq("account-id"), any());

    try {
        rateLimiterFilter.filter(mockContainerRequestContext);
    } catch (WebApplicationException e) {
        Response response = e.getResponse();
        assertEquals(429, response.getStatus());
        assertEquals("application/json", response.getHeaderString("Content-Type"));
        assertEquals("utf-8", response.getHeaderString("Content-Encoding"));
        assertEquals("{\"code\":\"P0900\",\"description\":\"Too many requests\"}", response.getEntity());
    }
}
 
Example 7
Source File: RestException.java    From pulsar with Apache License 2.0 5 votes vote down vote up
private static Response getResponse(Throwable t) {
    if (t instanceof WebApplicationException) {
        WebApplicationException e = (WebApplicationException) t;
        return e.getResponse();
    } else {
        return Response
            .status(Status.INTERNAL_SERVER_ERROR)
            .entity(getExceptionData(t))
            .type(MediaType.TEXT_PLAIN)
            .build();
    }
}
 
Example 8
Source File: WebApplicationExceptionHandler.java    From secure-data-service with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(WebApplicationException e) {
    if (e.getResponse().getStatus() == 500) {
        LOG.error("Caught exception thrown by ReST handler", e);
        Response.Status errorStatus = Response.Status.INTERNAL_SERVER_ERROR;
        
        return Response
                .status(errorStatus)
                .entity(new ErrorResponse(errorStatus.getStatusCode(), errorStatus.getReasonPhrase(),
                        "Internal Server Error: " + e.getMessage())).build();
    }
    return e.getResponse();
}
 
Example 9
Source File: FnFutureRequestHandlerTest.java    From jrestless with Apache License 2.0 5 votes vote down vote up
@Override
public Response toResponse(Exception exception) {
    if(exception instanceof WebApplicationException) {
        WebApplicationException wae = (WebApplicationException) exception;
        return wae.getResponse();
    }

    return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(GlobalExceptionMapper.class.getSimpleName())
            .build();
}
 
Example 10
Source File: AuthorizationUtilsTest.java    From cxf with Apache License 2.0 5 votes vote down vote up
@Test
public void testThrowAuthorizationFailureNoChallenge() {
    try {
        AuthorizationUtils.throwAuthorizationFailure(Collections.emptySet());
        fail("WebApplicationException expected");
    } catch (WebApplicationException ex) {
        Response r = ex.getResponse();
        assertEquals(401, r.getStatus());
        Object value = r.getMetadata().getFirst(HttpHeaders.WWW_AUTHENTICATE);
        assertNull(value);
    }
}
 
Example 11
Source File: MCRExceptionMapper.java    From mycore with GNU General Public License v3.0 5 votes vote down vote up
public static Response fromWebApplicationException(WebApplicationException wae) {
    if (wae.getResponse().hasEntity()) {
        //usually WAEs with entity do not arrive here
        LOGGER.warn("WebApplicationException already has an entity attached, forwarding response");
        return wae.getResponse();
    }
    final Response response = getResponse(wae, wae.getResponse().getStatus());
    response.getHeaders().putAll(wae.getResponse().getHeaders());
    return response;
}
 
Example 12
Source File: WebApplicationExceptionMapper.java    From cxf with Apache License 2.0 5 votes vote down vote up
public Response toResponse(WebApplicationException ex) {

        Response r = ex.getResponse();
        if (r == null) {
            r = Response.serverError().build();
        }
        boolean doAddMessage = r.getEntity() == null && addMessageToResponse;


        Message msg = PhaseInterceptorChain.getCurrentMessage();
        FaultListener flogger = null;
        if (msg != null) {
            flogger = (FaultListener)PhaseInterceptorChain.getCurrentMessage()
                .getContextualProperty(FaultListener.class.getName());
        }
        String errorMessage = doAddMessage || flogger != null
            ? buildErrorMessage(r, ex) : null;
        if (flogger == null
            || !flogger.faultOccurred(ex, errorMessage, msg)) {
            Level level = printStackTrace ? getStackTraceLogLevel(msg, r) : Level.FINE;
            LOG.log(level, ExceptionUtils.getStackTrace(ex));
        }

        if (doAddMessage) {
            r = JAXRSUtils.copyResponseIfNeeded(r);
            r = buildResponse(r, errorMessage);
        }
        return r;
    }
 
Example 13
Source File: WebApplicaitonExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception) {
    return exception.getResponse();
}
 
Example 14
Source File: WebApplicationExceptionMapper.java    From graviteeio-access-management with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse(final WebApplicationException e) {
    return e.getResponse();
}
 
Example 15
Source File: WebappExceptionMapper.java    From nexus-public with Eclipse Public License 1.0 4 votes vote down vote up
@Override
protected Response convert(final WebApplicationException exception, final String id) {
  return exception.getResponse();
}
 
Example 16
Source File: RetryOnGatewayTimeout.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
private static boolean isResponseGatewayTimedOut(WebApplicationException e) {
    try (Response response = e.getResponse()) {
        return response.getStatus() == HttpServletResponse.SC_GATEWAY_TIMEOUT;
    }
}
 
Example 17
Source File: WebApplicationExceptionHandler.java    From gazpachoquest with GNU General Public License v3.0 4 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception) {
    logger.warn("Handled error", exception);
    return exception.getResponse();
}
 
Example 18
Source File: WebApplicationExceptionMapper.java    From cloudbreak with Apache License 2.0 4 votes vote down vote up
@Override
public Response toResponse(WebApplicationException exception) {
    return exception.getResponse();
}
 
Example 19
Source File: DefaultExceptionMapper.java    From brooklyn-server with Apache License 2.0 4 votes vote down vote up
/**
 * Maps a throwable to a response.
 * <p/>
 * Returns {@link WebApplicationException#getResponse} if the exception is an instance of
 * {@link WebApplicationException}. Otherwise maps known exceptions to responses. If no
 * mapping is found a {@link Status#INTERNAL_SERVER_ERROR} is assumed.
 */
@Override
public Response toResponse(Throwable throwable1) {
    // EofException is thrown when the connection is reset,
    // for example when refreshing the browser window.
    // Don't depend on jetty, could be running in other environments as well.
    if (throwable1.getClass().getName().equals("org.eclipse.jetty.io.EofException")) {
        if (LOG.isTraceEnabled()) {
            LOG.trace("REST request running as {} was disconnected, threw: {}", Entitlements.getEntitlementContext(), 
                    Exceptions.collapse(throwable1));
        }
        return null;
    }

    Throwable throwable2 = Exceptions.getFirstInteresting(throwable1);
    if (isSevere(throwable2)) {
        LOG.warn("REST request running as {} threw: {}", Entitlements.getEntitlementContext(), 
            Exceptions.collapse(throwable1));
    } else {
        LOG.debug("REST request running as {} threw: {}", Entitlements.getEntitlementContext(), 
            Exceptions.collapse(throwable1));            
    }
    logExceptionDetailsForDebugging(throwable1);

    // Some methods will throw this, which gets converted automatically
    if (throwable2 instanceof WebApplicationException) {
        WebApplicationException wae = (WebApplicationException) throwable2;
        return wae.getResponse();
    }

    // The nicest way for methods to provide errors, wrap as this, and the stack trace will be suppressed
    if (throwable2 instanceof UserFacingException) {
        return ApiError.of(throwable2.getMessage()).asBadRequestResponseJson();
    }

    // For everything else, a trace is supplied
    
    // Assume ClassCoercionExceptions are caused by TypeCoercions from input parameters gone wrong
    // And IllegalArgumentException for malformed input parameters.
    if (throwable2 instanceof ClassCoercionException || throwable2 instanceof IllegalArgumentException) {
        return ApiError.of(throwable2).asBadRequestResponseJson();
    }

    // YAML exception 
    if (throwable2 instanceof YAMLException) {
        return ApiError.builder().message(throwable2.getMessage()).prefixMessage("Invalid YAML").build().asBadRequestResponseJson();
    }

    if (!Exceptions.isPrefixBoring(throwable2)) {
        if ( encounteredUnknownExceptions.add( throwable2.getClass() )) {
            LOG.warn("REST call generated exception type "+throwable2.getClass()+" unrecognized in "+getClass()+" (subsequent occurrences will be logged debug only): " + throwable2, throwable2);
        }
    }

    // Before saying server error, look for a user-facing exception anywhere in the hierarchy
    UserFacingException userFacing = Exceptions.getFirstThrowableOfType(throwable1, UserFacingException.class);
    if (userFacing instanceof UserFacingException) {
        return ApiError.of(userFacing.getMessage()).asBadRequestResponseJson();
    }
    
    Builder rb = ApiError.builderFromThrowable(Exceptions.collapse(throwable2));
    if (Strings.isBlank(rb.getMessage()))
        rb.message("Internal error. Contact server administrator to consult logs for more details.");
    return rb.build().asResponse(Status.INTERNAL_SERVER_ERROR, MediaType.APPLICATION_JSON_TYPE);
}
 
Example 20
Source File: WebApplicationExceptionMapper.java    From onos with Apache License 2.0 2 votes vote down vote up
/**
 * Extracts and returns the response from a WebApplicationException.
 *
 * @param e WebApplicationException that was thrown
 * @return precomputed Response from the exception
 */
@Override
public Response toResponse(WebApplicationException e) {
    return e.getResponse();
}