下面列出了怎么用javax.ws.rs.Consumes的API类实例代码及写法,或者点击链接到github查看源代码。
@PUT
@Path("/{namespace}/{key}")
@Consumes({MediaType.APPLICATION_OCTET_STREAM, MediaType.APPLICATION_FORM_URLENCODED, MediaType.MULTIPART_FORM_DATA, MediaType.TEXT_PLAIN})
@Operation(summary = "Add or overwrite an object in a namespace")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Object was added or existing content was overwritten"),
@ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response store(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
@Parameter(description = "Key of the object") @PathParam("key") final String key,
@Parameter(description = "Content of the object") final byte[] bytes) throws IOException {
logger.info("received request to store object with key '{}' in namespace {}", key, namespace);
logger.debug("object bytes: {}", bytes);
this.cantor.objects().store(namespace, key, bytes);
return Response.ok().build();
}
@POST()
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public $Type$Output updateModel_$name$(@PathParam("id") String id, $Type$ resource) {
return org.kie.kogito.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
ProcessInstance<$Type$> pi = process.instances()
.findById(id)
.orElse(null);
if (pi == null) {
return null;
} else {
pi.updateVariables(resource);
return mapOutput(new $Type$Output(), pi.variables());
}
});
}
@Path("/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createSheet(String title) throws Exception {
SpreadsheetProperties sheetProperties = new SpreadsheetProperties();
sheetProperties.setTitle(title);
Spreadsheet sheet = new Spreadsheet();
sheet.setProperties(sheetProperties);
Spreadsheet response = producerTemplate.requestBody("google-sheets://spreadsheets/create?inBody=content", sheet,
Spreadsheet.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response.getSpreadsheetId())
.build();
}
@ApiOperation(
value = "Validate application package",
notes = "Validate the application package ID for uniqueness",
response = Application.class,
responseContainer = "List"
)
@Path("/validatePkg")
@PUT
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response validateApplication(Application application) {
try {
final List<Application> otherApps = this.applicationDAO.getApplicationsForPackageID(application);
return Response.OK(otherApps);
} catch (Exception e) {
logger.error("Failed to validate application", e);
return Response.INTERNAL_ERROR();
}
}
@ResourceSecurity(INTERNAL_ONLY)
@POST
@Path("{taskId}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response createOrUpdateTask(@PathParam("taskId") TaskId taskId, TaskUpdateRequest taskUpdateRequest, @Context UriInfo uriInfo)
{
requireNonNull(taskUpdateRequest, "taskUpdateRequest is null");
Session session = taskUpdateRequest.getSession().toSession(sessionPropertyManager, taskUpdateRequest.getExtraCredentials());
TaskInfo taskInfo = taskManager.updateTask(session,
taskId,
taskUpdateRequest.getFragment(),
taskUpdateRequest.getSources(),
taskUpdateRequest.getOutputIds(),
taskUpdateRequest.getTotalPartitions());
if (shouldSummarize(uriInfo)) {
taskInfo = taskInfo.summarize();
}
return Response.ok().entity(taskInfo).build();
}
@ApiOperation(
value = "Update application configurations",
notes = "Updates the list of configurations using requested application"
)
@POST
@Path("/configurations")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response updateApplicationConfigurations(LinkConfigurationsToAppRequest request) {
try {
this.applicationDAO.updateApplicationConfigurations(request);
return Response.OK();
} catch (Exception e) {
logger.error("Unexpected error when updating application configurations", e);
return Response.INTERNAL_ERROR();
}
}
@Path("/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createMail(String message) throws Exception {
Message email = createMessage(message);
Map<String, Object> headers = new HashMap<>();
headers.put("CamelGoogleMail.userId", USER_ID);
headers.put("CamelGoogleMail.content", email);
final Message response = producerTemplate.requestBodyAndHeaders("google-mail://messages/send", null, headers,
Message.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response.getId())
.build();
}
@PATCH
@Path("/{id}")
@Consumes({RestConstants.MEDIA_TYPE_YAML, MediaType.APPLICATION_JSON})
@Operation(summary = "Update the experiment in the submarine server with spec",
tags = {"experiment"},
responses = {
@ApiResponse(description = "successful operation", content = @Content(
schema = @Schema(implementation = JsonResponse.class))),
@ApiResponse(responseCode = "404", description = "Experiment not found")})
public Response patchExperiment(@PathParam(RestConstants.ID) String id, ExperimentSpec spec) {
try {
Experiment experiment = experimentManager.patchExperiment(id, spec);
return new JsonResponse.Builder<Experiment>(Response.Status.OK).success(true)
.result(experiment).build();
} catch (SubmarineRuntimeException e) {
return parseExperimentServiceException(e);
}
}
@Path("/update")
@PATCH
@Consumes(MediaType.TEXT_PLAIN)
public Response updateSheet(@QueryParam("spreadsheetId") String spreadsheetId, String title) {
BatchUpdateSpreadsheetRequest request = new BatchUpdateSpreadsheetRequest()
.setIncludeSpreadsheetInResponse(true)
.setRequests(Collections
.singletonList(new Request().setUpdateSpreadsheetProperties(new UpdateSpreadsheetPropertiesRequest()
.setProperties(new SpreadsheetProperties().setTitle(title))
.setFields("title"))));
final Map<String, Object> headers = new HashMap<>();
headers.put("CamelGoogleSheets.spreadsheetId", spreadsheetId);
headers.put("CamelGoogleSheets.batchUpdateSpreadsheetRequest", request);
producerTemplate.requestBodyAndHeaders("google-sheets://spreadsheets/batchUpdate", null, headers);
return Response.ok().build();
}
@POST()
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public CompletionStage<$Type$Output> createResource_$name$(@Context HttpHeaders httpHeaders, @QueryParam("businessKey") String businessKey, $Type$Input resource) {
if (resource == null) {
resource = new $Type$Input();
}
final $Type$Input value = resource;
return CompletableFuture.supplyAsync(() -> {
return org.kie.kogito.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
ProcessInstance<$Type$> pi = process.createInstance(businessKey, mapInput(value, new $Type$()));
String startFromNode = httpHeaders.getHeaderString("X-KOGITO-StartFromNode");
if (startFromNode != null) {
pi.startFrom(startFromNode);
} else {
pi.start();
}
return getModel(pi);
});
});
}
@Path("/marshal/{soapVersion}")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_XML)
public Response marshall(@PathParam("soapVersion") String soapVersion, String message) throws Exception {
LOG.infof("Sending to soap: %s", message);
GetCustomersByName request = new GetCustomersByName();
request.setName(message);
final String endpointUri = "direct:marshal" + (soapVersion.equals("1.2") ? "-soap12" : "");
final String response = producerTemplate.requestBody(endpointUri, request, String.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}
@POST()
@Path("/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CompletionStage<$Type$Output> updateModel_$name$(@PathParam("id") String id, $Type$ resource) {
return CompletableFuture.supplyAsync(() -> {
return org.kie.kogito.services.uow.UnitOfWorkExecutor.executeInUnitOfWork(application.unitOfWorkManager(), () -> {
ProcessInstance<$Type$> pi = process.instances()
.findById(id)
.orElse(null);
if (pi == null) {
return null;
} else {
pi.updateVariables(resource);
return mapOutput(new $Type$Output(), pi.variables());
}
});
});
}
@POST // not supported by WebAppProxyServlet, can only be called directly
@Path(PATH_PHYSICAL_PLAN_OPERATORS + "/{operatorId:\\d+}/properties")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public JSONObject setPhysicalOperatorProperties(JSONObject request, @PathParam("operatorId") int operatorId)
{
init();
JSONObject response = new JSONObject();
try {
@SuppressWarnings("unchecked")
Iterator<String> keys = request.keys();
while (keys.hasNext()) {
String key = keys.next();
String val = request.isNull(key) ? null : request.getString(key);
dagManager.setPhysicalOperatorProperty(operatorId, key, val);
}
} catch (JSONException ex) {
LOG.warn("Got JSON Exception: ", ex);
}
return response;
}
@Path("/post")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response post(@QueryParam("jiraUrl") String jiraUrl, String message) throws Exception {
Map<String, Object> headers = new HashMap<>();
headers.put(JiraConstants.ISSUE_PROJECT_KEY, projectKey);
headers.put(JiraConstants.ISSUE_TYPE_NAME, "Task");
headers.put(JiraConstants.ISSUE_SUMMARY, "Demo Bug");
log.infof("Sending to jira: %s", message);
Issue issue = producerTemplate.requestBodyAndHeaders("jira:addIssue?jiraUrl=" + jiraUrl, message, headers, Issue.class);
log.infof("Created new issue: %s", issue.getKey());
return Response
.created(new URI("https://camel.apache.org/"))
.entity(issue.getKey())
.status(201)
.build();
}
@ApiOperation(
value = "Delete user",
notes = "Deletes a user account referenced by the specified ID"
)
@DELETE
@Path("/other/{id}")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response deleteUser(@PathParam("id") @ApiParam("User ID") int id) {
try {
userDAO.deleteUser(id);
return Response.OK();
} catch (Exception e) {
return Response.ERROR(e.getMessage());
}
}
@ApiOperation(
value = "Create or update plugin settings",
notes = "Creates a new plugin settings record (if id is not provided) or updates existing one otherwise",
authorizations = {@Authorization("Bearer Token")}
)
@PUT
@Path("/private")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response saveMainSettings(String settingsJSON) {
try {
ObjectMapper mapper = new ObjectMapper();
DeviceLogPluginSettings settings = mapper.readValue(settingsJSON, this.settingsDAO.getSettingsClass());
if (settings.getIdentifier() == null) {
this.settingsDAO.insertPluginSettings(settings);
} else {
this.settingsDAO.updatePluginSettings(settings);
}
return Response.OK();
} catch (Exception e) {
log.error("Failed to create or update device log plugin settings", e);
return Response.INTERNAL_ERROR();
}
}
@Path("/createPatient")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public Response createPatient(String patient) throws Exception {
MethodOutcome result = producerTemplate.requestBody("direct:create-dstu2", patient, MethodOutcome.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(result.getId().getIdPart())
.build();
}
@Path("/html-parse")
@POST
@Consumes(MediaType.TEXT_HTML)
@Produces(MediaType.TEXT_PLAIN)
public String htmlParse(String html) {
LOG.debugf("Parsing HTML %s", html);
return producerTemplate.requestBody(
XmlRouteBuilder.DIRECT_HTML_TO_DOM,
html,
String.class);
}
@Path("/fhir2xml")
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response fhir2xml(String patient) throws Exception {
try (InputStream response = producerTemplate.requestBody("direct:xml-to-r4", patient, InputStream.class)) {
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}
}
@Path("/fhir2json")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response fhir2json(String patient) throws Exception {
try (InputStream response = producerTemplate.requestBody("direct:json-to-dstu3", patient, InputStream.class)) {
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}
}
@POST
@Path("/schemas/{schemaid}/versions")
@Consumes({"application/json"})
@Produces({"application/json"})
public void apiSchemasSchemaidVersionsPost(
@Suspended AsyncResponse response,
@PathParam("schemaid") @NotNull String schemaid,
@NotNull @Valid NewSchemaVersion schema,
@DefaultValue("false") @QueryParam("verify") boolean verify
)
throws ArtifactNotFoundException {
service.apiSchemasSchemaidVersionsPost(response, schemaid, schema, verify);
}
@Path("/blob/create")
@POST
@Consumes(MediaType.TEXT_PLAIN)
public Response createBlob(String message) throws Exception {
BlobBlock blob = new BlobBlock(new ByteArrayInputStream(message.getBytes(StandardCharsets.UTF_8)));
producerTemplate.sendBody(
"azure-blob://devstoreaccount1/camel-test/test?operation=uploadBlobBlocks&azureBlobClient=#azureBlobClient&validateClientURI=false",
blob);
return Response.created(new URI("https://camel.apache.org/")).build();
}
@Path("/messages")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response postMessage(String message) throws Exception {
producerTemplate.requestBody(String.format("telegram://bots?chatId=%s", chatId), message);
log.infof("Sent a message to telegram %s", message);
return Response
.created(new URI(String.format("https://telegram.org/")))
.build();
}
@Path("/create/event")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createCalendarEvent(@QueryParam("calendarId") String calendarId, String eventText) throws Exception {
Map<String, Object> headers = new HashMap<>();
headers.put("CamelGoogleCalendar.calendarId", calendarId);
headers.put("CamelGoogleCalendar.text", eventText);
Event response = producerTemplate.requestBodyAndHeaders("google-calendar://events/quickAdd", null, headers,
Event.class);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response.getId())
.build();
}
@Path("/marshal-firstname")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_XML)
public Response marshallFirstName(String name) throws Exception {
Person p = new Person();
p.setFirstName(name);
String response = producerTemplate.requestBody("direct:marshal", p, String.class);
LOG.infof("Got response from jaxb=>: %s", response);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response getIcons() {
try {
final List<Icon> allIcons = this.iconDAO.getAllIcons();
return Response.OK(allIcons);
} catch (Exception e) {
return Response.INTERNAL_ERROR();
}
}
@Path("/http/post")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String httpPost(@QueryParam("test-port") int port, String message) {
return producerTemplate
.to("http://localhost:" + port + "/service/toUpper?bridgeEndpoint=true")
.withBody(message)
.withHeader(Exchange.CONTENT_TYPE, MediaType.TEXT_PLAIN)
.withHeader(Exchange.HTTP_METHOD, "POST")
.request(String.class);
}
@Path("/queue/message")
@POST
@Consumes(MediaType.TEXT_PLAIN)
public Response addMessage(String message) throws Exception {
producerTemplate.sendBody(
"azure-queue://devstoreaccount1/" + QUEUE_NAME
+ "?operation=addMessage&azureQueueClient=#azureQueueClient&validateClientURI=false",
message);
return Response.created(new URI("https://camel.apache.org/")).build();
}
@Path("/json-to-csv")
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String json2csv(String json) throws Exception {
LOG.infof("Transforming json %s", json);
final List<Map<String, Object>> objects = new ObjectMapper().readValue(json,
new TypeReference<List<Map<String, Object>>>() {
});
return producerTemplate.requestBody(
"direct:json-to-csv",
objects,
String.class);
}
@Path("/blob/update")
@PATCH
@Consumes(MediaType.TEXT_PLAIN)
public Response updateBlob(String message) throws Exception {
producerTemplate.sendBody(
"azure-blob://devstoreaccount1/camel-test/test?operation=updateBlockBlob&azureBlobClient=#azureBlobClient&validateClientURI=false",
message);
return Response.ok().build();
}