Search in sources :

Example 71 with Consumes

use of javax.ws.rs.Consumes in project killbill by killbill.

the class InvoiceResource method adjustInvoiceItem.

@TimedResource
@POST
@Path("/{invoiceId:" + UUID_PATTERN + "}")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@ApiOperation(value = "Adjust an invoice item")
@ApiResponses(value = { @ApiResponse(code = 400, message = "Invalid account id, invoice id or invoice item id supplied"), @ApiResponse(code = 404, message = "Invoice not found") })
public Response adjustInvoiceItem(final InvoiceItemJson json, @PathParam("invoiceId") final String invoiceId, @QueryParam(QUERY_REQUESTED_DT) final String requestedDateTimeString, @HeaderParam(HDR_CREATED_BY) final String createdBy, @HeaderParam(HDR_REASON) final String reason, @HeaderParam(HDR_COMMENT) final String comment, @javax.ws.rs.core.Context final HttpServletRequest request, @javax.ws.rs.core.Context final UriInfo uriInfo) throws AccountApiException, InvoiceApiException {
    verifyNonNullOrEmpty(json, "InvoiceItemJson body should be specified");
    verifyNonNullOrEmpty(json.getAccountId(), "InvoiceItemJson accountId needs to be set", json.getInvoiceItemId(), "InvoiceItemJson invoiceItemId needs to be set");
    final CallContext callContext = context.createContext(createdBy, reason, comment, request);
    final UUID accountId = UUID.fromString(json.getAccountId());
    final LocalDate requestedDate = toLocalDateDefaultToday(accountId, requestedDateTimeString, callContext);
    final InvoiceItem adjustmentItem;
    if (json.getAmount() == null) {
        adjustmentItem = invoiceApi.insertInvoiceItemAdjustment(accountId, UUID.fromString(invoiceId), UUID.fromString(json.getInvoiceItemId()), requestedDate, json.getDescription(), callContext);
    } else {
        adjustmentItem = invoiceApi.insertInvoiceItemAdjustment(accountId, UUID.fromString(invoiceId), UUID.fromString(json.getInvoiceItemId()), requestedDate, json.getAmount(), Currency.valueOf(json.getCurrency()), json.getDescription(), callContext);
    }
    return uriBuilder.buildResponse(uriInfo, InvoiceResource.class, "getInvoice", adjustmentItem.getInvoiceId(), request);
}
Also used : InvoiceItem(org.killbill.billing.invoice.api.InvoiceItem) UUID(java.util.UUID) CallContext(org.killbill.billing.util.callcontext.CallContext) LocalDate(org.joda.time.LocalDate) Path(javax.ws.rs.Path) TimedResource(org.killbill.commons.metrics.TimedResource) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) ApiOperation(io.swagger.annotations.ApiOperation) ApiResponses(io.swagger.annotations.ApiResponses)

Example 72 with Consumes

use of javax.ws.rs.Consumes 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 73 with Consumes

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

the class RequestTokenResource method postReqTokenRequest.

/**
     * POST method for creating a request for a Request Token.
     *
     * @return an HTTP response with content of the updated or created resource.
     */
@POST
@Consumes("application/x-www-form-urlencoded")
@Produces("application/x-www-form-urlencoded")
@TokenResource
public Response postReqTokenRequest() {
    OAuthServerRequest request = new OAuthServerRequest(requestContext);
    OAuth1Parameters params = new OAuth1Parameters();
    params.readRequest(request);
    String tok = params.getToken();
    if ((tok != null) && (!tok.contentEquals(""))) {
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    String consKey = params.getConsumerKey();
    if (consKey == null) {
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    OAuth1Consumer consumer = provider.getConsumer(consKey);
    if (consumer == null) {
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    OAuth1Secrets secrets = new OAuth1Secrets().consumerSecret(consumer.getSecret()).tokenSecret("");
    boolean sigIsOk = false;
    try {
        sigIsOk = oAuth1Signature.verify(request, params, secrets);
    } catch (OAuth1SignatureException ex) {
        Logger.getLogger(RequestTokenResource.class.getName()).log(Level.SEVERE, null, ex);
    }
    if (!sigIsOk) {
        throw new OAuth1Exception(Response.Status.BAD_REQUEST, null);
    }
    MultivaluedMap<String, String> parameters = new MultivaluedHashMap<String, String>();
    for (String n : request.getParameterNames()) {
        parameters.put(n, request.getParameterValues(n));
    }
    OAuth1Token rt = provider.newRequestToken(consKey, params.getCallback(), parameters);
    Form resp = new Form();
    resp.param(OAuth1Parameters.TOKEN, rt.getToken());
    resp.param(OAuth1Parameters.TOKEN_SECRET, rt.getSecret());
    resp.param(OAuth1Parameters.CALLBACK_CONFIRMED, "true");
    return Response.ok(resp).build();
}
Also used : 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) MultivaluedHashMap(javax.ws.rs.core.MultivaluedHashMap) 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 74 with Consumes

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

the class MultiPartResource method ten.

@Path("ten")
@PUT
@Consumes("multipart/mixed")
@Produces("text/plain")
public Response ten(MultiPart mp) {
    if (!(mp.getBodyParts().size() == 2)) {
        return Response.ok("FAILED:  Body part count is " + mp.getBodyParts().size() + " instead of 2").build();
    } else if (!(mp.getBodyParts().get(1).getEntity() instanceof BodyPartEntity)) {
        return Response.ok("FAILED:  Second body part is " + mp.getBodyParts().get(1).getClass().getName() + " instead of BodyPartEntity").build();
    }
    BodyPartEntity bpe = (BodyPartEntity) mp.getBodyParts().get(1).getEntity();
    try {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        InputStream stream = bpe.getInputStream();
        byte[] buffer = new byte[2048];
        while (true) {
            int n = stream.read(buffer);
            if (n < 0) {
                break;
            }
            baos.write(buffer, 0, n);
        }
        if (baos.toByteArray().length > 0) {
            return Response.ok("FAILED:  Second body part had " + baos.toByteArray().length + " bytes instead of 0").build();
        }
        return Response.ok("SUCCESS:  All tests passed").build();
    } catch (IOException e) {
        return Response.ok("FAILED:  Threw IOException").build();
    }
}
Also used : InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) BodyPartEntity(org.glassfish.jersey.media.multipart.BodyPartEntity) Path(javax.ws.rs.Path) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) PUT(javax.ws.rs.PUT)

Example 75 with Consumes

use of javax.ws.rs.Consumes 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)

Aggregations

Consumes (javax.ws.rs.Consumes)1610 Path (javax.ws.rs.Path)1243 Produces (javax.ws.rs.Produces)1233 POST (javax.ws.rs.POST)917 ApiOperation (io.swagger.annotations.ApiOperation)508 ApiResponses (io.swagger.annotations.ApiResponses)445 PUT (javax.ws.rs.PUT)439 GET (javax.ws.rs.GET)224 CheckPermission (com.emc.storageos.security.authorization.CheckPermission)215 URI (java.net.URI)207 IOException (java.io.IOException)160 ArrayList (java.util.ArrayList)142 WebApplicationException (javax.ws.rs.WebApplicationException)142 Response (javax.ws.rs.core.Response)140 Authorizable (org.apache.nifi.authorization.resource.Authorizable)100 DELETE (javax.ws.rs.DELETE)87 TimedResource (org.killbill.commons.metrics.TimedResource)84 CallContext (org.killbill.billing.util.callcontext.CallContext)83 Timed (com.codahale.metrics.annotation.Timed)78 HashMap (java.util.HashMap)78