Search in sources :

Example 26 with WebApplicationException

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

the class BasicTypesMessageProvider method readFrom.

@Override
public Object readFrom(Class<Object> type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) throws IOException, WebApplicationException {
    final String entityString = readFromAsString(entityStream, mediaType);
    if (entityString.isEmpty()) {
        throw new NoContentException(LocalizationMessages.ERROR_READING_ENTITY_MISSING());
    }
    final PrimitiveTypes primitiveType = PrimitiveTypes.forType(type);
    if (primitiveType != null) {
        return primitiveType.convert(entityString);
    }
    final Constructor constructor = AccessController.doPrivileged(ReflectionHelper.getStringConstructorPA(type));
    if (constructor != null) {
        try {
            return type.cast(constructor.newInstance(entityString));
        } catch (Exception e) {
            throw new MessageBodyProcessingException(LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_CONSTRUCTOR(type));
        }
    }
    if (AtomicInteger.class.isAssignableFrom(type)) {
        return new AtomicInteger((Integer) PrimitiveTypes.INTEGER.convert(entityString));
    }
    if (AtomicLong.class.isAssignableFrom(type)) {
        return new AtomicLong((Long) PrimitiveTypes.LONG.convert(entityString));
    }
    throw new MessageBodyProcessingException(LocalizationMessages.ERROR_ENTITY_PROVIDER_BASICTYPES_UNKWNOWN(type));
}
Also used : AtomicLong(java.util.concurrent.atomic.AtomicLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Constructor(java.lang.reflect.Constructor) NoContentException(javax.ws.rs.core.NoContentException) NoContentException(javax.ws.rs.core.NoContentException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException)

Example 27 with WebApplicationException

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

the class ExceptionResource method testWebApplicationExceptionEntity.

@POST
@Path("webapplication_entity")
public String testWebApplicationExceptionEntity(String s) {
    String[] tokens = s.split(":");
    assert tokens.length == 2;
    int statusCode = Integer.valueOf(tokens[1]);
    Response r = Response.status(statusCode).entity(s).build();
    throw new WebApplicationException(r);
}
Also used : Response(javax.ws.rs.core.Response) WebApplicationException(javax.ws.rs.WebApplicationException) Path(javax.ws.rs.Path) POST(javax.ws.rs.POST)

Example 28 with WebApplicationException

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

the class RequestUtil method getEntityParameters.

/**
     * Returns the form parameters from a request entity as a multi-valued map.
     * If the request does not have a POST method, or the media type is not
     * x-www-form-urlencoded, then null is returned.
     *
     * @param request the client request containing the entity to extract parameters from.
     * @return a {@link javax.ws.rs.core.MultivaluedMap} containing the entity form parameters.
     */
@SuppressWarnings("unchecked")
public static MultivaluedMap<String, String> getEntityParameters(ClientRequestContext request, MessageBodyWorkers messageBodyWorkers) {
    Object entity = request.getEntity();
    String method = request.getMethod();
    MediaType mediaType = request.getMediaType();
    // no entity, not a post or not x-www-form-urlencoded: return empty map
    if (entity == null || method == null || !HttpMethod.POST.equalsIgnoreCase(method) || mediaType == null || !mediaType.equals(MediaType.APPLICATION_FORM_URLENCODED_TYPE)) {
        return new MultivaluedHashMap<String, String>();
    }
    // it's ready to go if already expressed as a multi-valued map
    if (entity instanceof MultivaluedMap) {
        return (MultivaluedMap<String, String>) entity;
    }
    Type entityType = entity.getClass();
    // if the entity is generic, get specific type and class
    if (entity instanceof GenericEntity) {
        final GenericEntity generic = (GenericEntity) entity;
        // overwrite
        entityType = generic.getType();
        entity = generic.getEntity();
    }
    final Class entityClass = entity.getClass();
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    MessageBodyWriter writer = messageBodyWorkers.getMessageBodyWriter(entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    try {
        writer.writeTo(entity, entityClass, entityType, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, out);
    } catch (WebApplicationException wae) {
        throw new IllegalStateException(wae);
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
    ByteArrayInputStream in = new ByteArrayInputStream(out.toByteArray());
    MessageBodyReader reader = messageBodyWorkers.getMessageBodyReader(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE);
    try {
        return (MultivaluedMap<String, String>) reader.readFrom(MultivaluedMap.class, MultivaluedMap.class, EMPTY_ANNOTATIONS, MediaType.APPLICATION_FORM_URLENCODED_TYPE, null, in);
    } catch (IOException ioe) {
        throw new IllegalStateException(ioe);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) MessageBodyReader(javax.ws.rs.ext.MessageBodyReader) MediaType(javax.ws.rs.core.MediaType) Type(java.lang.reflect.Type) ByteArrayInputStream(java.io.ByteArrayInputStream) GenericEntity(javax.ws.rs.core.GenericEntity) MediaType(javax.ws.rs.core.MediaType) MultivaluedMap(javax.ws.rs.core.MultivaluedMap) MessageBodyWriter(javax.ws.rs.ext.MessageBodyWriter)

Example 29 with WebApplicationException

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

the class AccessTokenResource method postAccessTokenRequest.

/**
     * POST method for creating a request for Request Token.
     * @return an HTTP response with content of the updated or created resource.
     */
@POST
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.APPLICATION_FORM_URLENCODED)
@TokenResource
public Response postAccessTokenRequest(@Context ContainerRequestContext requestContext, @Context Request req) {
    boolean sigIsOk = false;
    OAuthServerRequest request = new OAuthServerRequest(requestContext);
    OAuth1Parameters params = new OAuth1Parameters();
    params.readRequest(request);
    if (params.getToken() == null) {
        throw new WebApplicationException(new Throwable("oauth_token MUST be present."), 400);
    }
    String consKey = params.getConsumerKey();
    if (consKey == null) {
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    OAuth1Token rt = provider.getRequestToken(params.getToken());
    if (rt == null) {
        // token invalid
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    OAuth1Consumer consumer = rt.getConsumer();
    if (consumer == null || !consKey.equals(consumer.getKey())) {
        // token invalid
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    OAuth1Secrets secrets = new OAuth1Secrets().consumerSecret(consumer.getSecret()).tokenSecret(rt.getSecret());
    try {
        sigIsOk = oAuth1Signature.verify(request, params, secrets);
    } catch (OAuth1SignatureException ex) {
        Logger.getLogger(AccessTokenResource.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (!sigIsOk) {
        // signature invalid
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    // We're good to go.
    OAuth1Token at = provider.newAccessToken(rt, params.getVerifier());
    if (at == null) {
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    // Preparing the response.
    Form resp = new Form();
    resp.param(OAuth1Parameters.TOKEN, at.getToken());
    resp.param(OAuth1Parameters.TOKEN_SECRET, at.getSecret());
    resp.asMap().putAll(at.getAttributes());
    return Response.ok(resp).build();
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Form(javax.ws.rs.core.Form) OAuth1Consumer(org.glassfish.jersey.server.oauth1.OAuth1Consumer) OAuth1SignatureException(org.glassfish.jersey.oauth1.signature.OAuth1SignatureException) OAuth1Secrets(org.glassfish.jersey.oauth1.signature.OAuth1Secrets) OAuth1Parameters(org.glassfish.jersey.oauth1.signature.OAuth1Parameters) OAuth1Exception(org.glassfish.jersey.server.oauth1.OAuth1Exception) OAuth1Token(org.glassfish.jersey.server.oauth1.OAuth1Token) TokenResource(org.glassfish.jersey.server.oauth1.TokenResource) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces)

Example 30 with WebApplicationException

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

the class MessageBodyReaderTestFormat method readFrom.

@Override
public Message readFrom(final Class<Message> type, final Type genericType, final Annotation[] annotations, final MediaType mediaType, final MultivaluedMap<String, String> httpHeaders, final InputStream entityStream) throws IOException, WebApplicationException {
    final BufferedReader reader = new BufferedReader(new InputStreamReader(entityStream, MessageUtils.getCharset(mediaType)));
    final String line = reader.readLine();
    if (line == null || !line.startsWith(Utils.FORMAT_PREFIX) || !line.endsWith(Utils.FORMAT_SUFFIX)) {
        throw new WebApplicationException(new IllegalArgumentException("Input content '" + line + "' is not in a valid format!"));
    }
    final String text = line.substring(Utils.FORMAT_PREFIX.length(), line.length() - Utils.FORMAT_SUFFIX.length());
    if (serverSide) {
        Utils.throwException(text, this, Utils.TestAction.MESSAGE_BODY_READER_THROW_WEB_APPLICATION, Utils.TestAction.MESSAGE_BODY_READER_THROW_PROCESSING, Utils.TestAction.MESSAGE_BODY_READER_THROW_ANY);
    }
    return new Message(text);
}
Also used : InputStreamReader(java.io.InputStreamReader) WebApplicationException(javax.ws.rs.WebApplicationException) BufferedReader(java.io.BufferedReader)

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