Search in sources :

Example 51 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 52 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)

Example 53 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project druid by druid-io.

the class SqlResource method doPost.

@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response doPost(final SqlQuery sqlQuery) throws SQLException, IOException {
    // This is not integrated with the experimental authorization framework.
    // (Non-trivial since we don't know the dataSources up-front)
    final PlannerResult plannerResult;
    final DateTimeZone timeZone;
    try (final DruidPlanner planner = plannerFactory.createPlanner(sqlQuery.getContext())) {
        plannerResult = planner.plan(sqlQuery.getQuery());
        timeZone = planner.getPlannerContext().getTimeZone();
        // Remember which columns are time-typed, so we can emit ISO8601 instead of millis values.
        final List<RelDataTypeField> fieldList = plannerResult.rowType().getFieldList();
        final boolean[] timeColumns = new boolean[fieldList.size()];
        final boolean[] dateColumns = new boolean[fieldList.size()];
        for (int i = 0; i < fieldList.size(); i++) {
            final SqlTypeName sqlTypeName = fieldList.get(i).getType().getSqlTypeName();
            timeColumns[i] = sqlTypeName == SqlTypeName.TIMESTAMP;
            dateColumns[i] = sqlTypeName == SqlTypeName.DATE;
        }
        final Yielder<Object[]> yielder0 = Yielders.each(plannerResult.run());
        try {
            return Response.ok(new StreamingOutput() {

                @Override
                public void write(final OutputStream outputStream) throws IOException, WebApplicationException {
                    Yielder<Object[]> yielder = yielder0;
                    try (final JsonGenerator jsonGenerator = jsonMapper.getFactory().createGenerator(outputStream)) {
                        jsonGenerator.writeStartArray();
                        while (!yielder.isDone()) {
                            final Object[] row = yielder.get();
                            jsonGenerator.writeStartObject();
                            for (int i = 0; i < fieldList.size(); i++) {
                                final Object value;
                                if (timeColumns[i]) {
                                    value = ISODateTimeFormat.dateTime().print(Calcites.calciteTimestampToJoda((long) row[i], timeZone));
                                } else if (dateColumns[i]) {
                                    value = ISODateTimeFormat.dateTime().print(Calcites.calciteDateToJoda((int) row[i], timeZone));
                                } else {
                                    value = row[i];
                                }
                                jsonGenerator.writeObjectField(fieldList.get(i).getName(), value);
                            }
                            jsonGenerator.writeEndObject();
                            yielder = yielder.next(null);
                        }
                        jsonGenerator.writeEndArray();
                        jsonGenerator.flush();
                        // End with CRLF
                        outputStream.write('\r');
                        outputStream.write('\n');
                    } finally {
                        yielder.close();
                    }
                }
            }).build();
        } catch (Throwable e) {
            // make sure to close yielder if anything happened before starting to serialize the response.
            yielder0.close();
            throw Throwables.propagate(e);
        }
    } catch (Exception e) {
        log.warn(e, "Failed to handle query: %s", sqlQuery);
        final Exception exceptionToReport;
        if (e instanceof RelOptPlanner.CannotPlanException) {
            exceptionToReport = new ISE("Cannot build plan for query: %s", sqlQuery.getQuery());
        } else {
            exceptionToReport = e;
        }
        return Response.serverError().type(MediaType.APPLICATION_JSON_TYPE).entity(jsonMapper.writeValueAsBytes(QueryInterruptedException.wrapIfNeeded(exceptionToReport))).build();
    }
}
Also used : SqlTypeName(org.apache.calcite.sql.type.SqlTypeName) OutputStream(java.io.OutputStream) StreamingOutput(javax.ws.rs.core.StreamingOutput) RelOptPlanner(org.apache.calcite.plan.RelOptPlanner) DateTimeZone(org.joda.time.DateTimeZone) QueryInterruptedException(io.druid.query.QueryInterruptedException) SQLException(java.sql.SQLException) IOException(java.io.IOException) WebApplicationException(javax.ws.rs.WebApplicationException) RelDataTypeField(org.apache.calcite.rel.type.RelDataTypeField) DruidPlanner(io.druid.sql.calcite.planner.DruidPlanner) JsonGenerator(com.fasterxml.jackson.core.JsonGenerator) ISE(io.druid.java.util.common.ISE) PlannerResult(io.druid.sql.calcite.planner.PlannerResult) POST(javax.ws.rs.POST) Produces(javax.ws.rs.Produces) Consumes(javax.ws.rs.Consumes)

Example 54 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project druid by druid-io.

the class ConfigResourceFilter method filter.

@Override
public ContainerRequest filter(ContainerRequest request) {
    if (getAuthConfig().isEnabled()) {
        // This is an experimental feature, see - https://github.com/druid-io/druid/pull/2424
        final String resourceName = "CONFIG";
        final AuthorizationInfo authorizationInfo = (AuthorizationInfo) getReq().getAttribute(AuthConfig.DRUID_AUTH_TOKEN);
        Preconditions.checkNotNull(authorizationInfo, "Security is enabled but no authorization info found in the request");
        final Access authResult = authorizationInfo.isAuthorized(new Resource(resourceName, ResourceType.CONFIG), getAction(request));
        if (!authResult.isAllowed()) {
            throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(String.format("Access-Check-Result: %s", authResult.toString())).build());
        }
    }
    return request;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Access(io.druid.server.security.Access) Resource(io.druid.server.security.Resource) AuthorizationInfo(io.druid.server.security.AuthorizationInfo)

Example 55 with WebApplicationException

use of javax.ws.rs.WebApplicationException in project druid by druid-io.

the class RulesResourceFilter method filter.

@Override
public ContainerRequest filter(ContainerRequest request) {
    if (getAuthConfig().isEnabled()) {
        // This is an experimental feature, see - https://github.com/druid-io/druid/pull/2424
        final String dataSourceName = request.getPathSegments().get(Iterables.indexOf(request.getPathSegments(), new Predicate<PathSegment>() {

            @Override
            public boolean apply(PathSegment input) {
                return input.getPath().equals("rules");
            }
        }) + 1).getPath();
        Preconditions.checkNotNull(dataSourceName);
        final AuthorizationInfo authorizationInfo = (AuthorizationInfo) getReq().getAttribute(AuthConfig.DRUID_AUTH_TOKEN);
        Preconditions.checkNotNull(authorizationInfo, "Security is enabled but no authorization info found in the request");
        final Access authResult = authorizationInfo.isAuthorized(new Resource(dataSourceName, ResourceType.DATASOURCE), getAction(request));
        if (!authResult.isAllowed()) {
            throw new WebApplicationException(Response.status(Response.Status.FORBIDDEN).entity(String.format("Access-Check-Result: %s", authResult.toString())).build());
        }
    }
    return request;
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) Access(io.druid.server.security.Access) Resource(io.druid.server.security.Resource) PathSegment(javax.ws.rs.core.PathSegment) AuthorizationInfo(io.druid.server.security.AuthorizationInfo) Predicate(com.google.common.base.Predicate)

Aggregations

WebApplicationException (javax.ws.rs.WebApplicationException)435 Produces (javax.ws.rs.Produces)91 IOException (java.io.IOException)88 Path (javax.ws.rs.Path)81 GET (javax.ws.rs.GET)80 POST (javax.ws.rs.POST)58 Response (javax.ws.rs.core.Response)56 Consumes (javax.ws.rs.Consumes)53 Test (org.junit.Test)51 ResponseBuilder (javax.ws.rs.core.Response.ResponseBuilder)46 HashMap (java.util.HashMap)36 URI (java.net.URI)34 MediaType (javax.ws.rs.core.MediaType)31 ArrayList (java.util.ArrayList)30 List (java.util.List)23 InputStream (java.io.InputStream)22 ByteArrayInputStream (java.io.ByteArrayInputStream)21 WebClient (org.apache.cxf.jaxrs.client.WebClient)21 JSONObject (org.codehaus.jettison.json.JSONObject)20 ProcessingException (javax.ws.rs.ProcessingException)19