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);
}
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();
}
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();
}
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();
}
}
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();
}
}
Aggregations