Search in sources :

Example 16 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project dropwizard by dropwizard.

the class FuzzyEnumParamConverterProvider method getConverter.

@Override
public <T> ParamConverter<T> getConverter(Class<T> rawType, Type genericType, Annotation[] annotations) {
    if (!rawType.isEnum()) {
        return null;
    }
    final Class<Enum<?>> type = (Class<Enum<?>>) rawType;
    final Enum<?>[] constants = type.getEnumConstants();
    final String parameterName = getParameterNameFromAnnotations(annotations).orElse("Parameter");
    return new ParamConverter<T>() {

        @Override
        public T fromString(String value) {
            if (Strings.isNullOrEmpty(value)) {
                return null;
            }
            final Enum<?> constant = Enums.fromStringFuzzy(value, constants);
            if (constant != null) {
                return (T) constant;
            }
            final String errMsg = String.format("%s must be one of [%s]", parameterName, JOINER.join(constants));
            throw new WebApplicationException(getErrorResponse(errMsg));
        }

        @Override
        public String toString(T value) {
            return value.toString();
        }

        protected Response getErrorResponse(String message) {
            return Response.status(400).entity(new ErrorMessage(400, message)).type(MediaType.APPLICATION_JSON_TYPE).build();
        }
    };
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ParamConverter(javax.ws.rs.ext.ParamConverter) ErrorMessage(io.dropwizard.jersey.errors.ErrorMessage)

Example 17 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project dropwizard by dropwizard.

the class LoggingExceptionMapper method toResponse.

@Override
public Response toResponse(E exception) {
    // redirection or server errors) better and also propagate properties of the inner response.
    if (exception instanceof WebApplicationException) {
        final Response response = ((WebApplicationException) exception).getResponse();
        Response.Status.Family family = response.getStatusInfo().getFamily();
        if (family.equals(Response.Status.Family.REDIRECTION)) {
            return response;
        }
        if (family.equals(Response.Status.Family.SERVER_ERROR)) {
            logException(exception);
        }
        return Response.fromResponse(response).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(response.getStatus(), exception.getLocalizedMessage())).build();
    }
    // Else the thrown exception is a not a web exception, so the exception is most likely
    // unexpected. We'll create a unique id in the server error response that is also logged for
    // correlation
    final long id = logException(exception);
    return Response.status(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()).type(MediaType.APPLICATION_JSON_TYPE).entity(new ErrorMessage(formatErrorMessage(id, exception))).build();
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 18 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project dropwizard by dropwizard.

the class LoggingExceptionMapperTest method handlesMethodNotAllowedWithHeaders.

@Test
public void handlesMethodNotAllowedWithHeaders() {
    final Throwable thrown = catchThrowable(() -> target("/exception/json-mapping-exception").request(MediaType.APPLICATION_JSON).post(Entity.json("A"), String.class));
    assertThat(thrown).isInstanceOf(WebApplicationException.class);
    final Response resp = ((WebApplicationException) thrown).getResponse();
    assertThat(resp.getStatus()).isEqualTo(405);
    assertThat(resp.getHeaders()).contains(entry("Allow", ImmutableList.of("GET,OPTIONS")));
    assertThat(resp.readEntity(String.class)).isEqualTo("{\"code\":405,\"message\":\"HTTP 405 Method Not Allowed\"}");
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) Assertions.catchThrowable(org.assertj.core.api.Assertions.catchThrowable) AbstractJerseyTest(io.dropwizard.jersey.AbstractJerseyTest) Test(org.junit.Test)

Example 19 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project eureka by Netflix.

the class DiscoveryJerseyProvider method writeTo.

@Override
public void writeTo(Object serializableObject, Class serializableClass, Type type, Annotation[] annotations, MediaType mediaType, MultivaluedMap headers, OutputStream outputStream) throws IOException, WebApplicationException {
    EncoderWrapper encoder = "json".equalsIgnoreCase(mediaType.getSubtype()) ? jsonEncoder : xmlEncoder;
    // XML codec may not be available
    if (encoder == null) {
        throw new WebApplicationException(createErrorReply(400, "No codec available to serialize content type " + mediaType, mediaType));
    }
    encoder.encode(serializableObject, outputStream);
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) EncoderWrapper(com.netflix.discovery.converters.wrappers.EncoderWrapper)

Example 20 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project OpenAttestation by OpenAttestation.

the class AbstractJsonapiResource method storeJsonapiCollection.

/**
     * Replace an item in the collection. Input Content-Type is
     * application/vnd.api+json Output Content-Type is application/vnd.api+json
     *
     * The input item must be wrapped in a collection. The output item is always
     * wrapped in a collection.
     *
     * @param locator
     * @param collection
     * @return
     */
@Path("/{id}")
@PUT
@Consumes(DataMediaType.APPLICATION_VND_API_JSON)
@Produces(DataMediaType.APPLICATION_VND_API_JSON)
public C storeJsonapiCollection(@BeanParam L locator, C collection) {
    // misnomer, what we really mean is "store one but wrapped ina  collection for jsonapi"
    log.debug("storeCollection");
    ValidationUtil.validate(collection);
    List<T> list = collection.getDocuments();
    if (list == null || list.isEmpty()) {
        throw new WebApplicationException(Response.Status.BAD_REQUEST);
    }
    T item = list.get(0);
    locator.copyTo(item);
    if (item == null) {
        getRepository().create(item);
    } else {
        getRepository().store(item);
    }
    return collection;
}
Also used : POST(javax.ws.rs.POST) GET(javax.ws.rs.GET) PUT(javax.ws.rs.PUT) WebApplicationException(javax.ws.rs.WebApplicationException) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)276 Produces (javax.ws.rs.Produces)77 GET (javax.ws.rs.GET)71 Path (javax.ws.rs.Path)69 IOException (java.io.IOException)47 POST (javax.ws.rs.POST)47 Consumes (javax.ws.rs.Consumes)44 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)43 Response (javax.ws.rs.core.Response)30 MediaType (javax.ws.rs.core.MediaType)26 URI (java.net.URI)25 HashMap (java.util.HashMap)20 JSONObject (org.codehaus.jettison.json.JSONObject)20 Test (org.junit.Test)19 JSONException (org.codehaus.jettison.json.JSONException)18 ApiOperation (io.swagger.annotations.ApiOperation)17 ArrayList (java.util.ArrayList)17 ByteArrayInputStream (java.io.ByteArrayInputStream)15 Viewable (org.apache.stanbol.commons.web.viewable.Viewable)15 List (java.util.List)14