下面列出了javax.servlet.http.HttpServletRequestWrapper#javax.ws.rs.POST 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response login(LoginRequest request) {
var payload = new LoginResponse();
if (!service.verifyLogin(request)) {
throw new NotAuthorizedException("Invalid user and/or password");
}
var user = PersistenceManager.getInstance().getById(User.class, request.getUsername());
payload.setToken(service.createToken(user));
// TODO: max age, etc.
return Response.ok(payload).cookie(new NewCookie("authorization", payload.getToken())).build();
}
/**
* Client off common response.
*
* @param request the request
* @return the common response
*/
@POST
@Path("/off")
public CommonResponse clientOff(CancelAddressRequest request) {
if (null == request) {
return CommonResponse.buildFailedResponse("Request can not be null.");
}
if (CollectionUtils.isEmpty(request.getConnectIds())) {
return CommonResponse.buildFailedResponse("ConnectIds can not be null.");
}
final List<String> connectIds = request.getConnectIds();
sessionRegistry.cancel(connectIds);
return CommonResponse.buildSuccessResponse();
}
@POST
@Path("query")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public GeneralResponse<?> query(RuleQueryRequest param, @Context HttpServletRequest request) {
if (param == null) {
param = new RuleQueryRequest();
}
// Get login user
param.setUser(HttpUtils.getUserName(request));
try {
List<RuleQueryProject> results = ruleQueryService.query(param);
LOG.info("[My DataSource] Query successfully. The number of results:{}", results == null ? 0 : results.size());
return new GeneralResponse<>("200", "{&QUERY_SUCCESSFULLY}", results);
} catch (Exception e) {
LOG.error("[My DataSource] Query failed, internal error.", e);
return new GeneralResponse<>("500", e.getMessage(), null);
}
}
@POST
@Path("remove")
@Produces(MediaType.APPLICATION_JSON)
public Result remove(PersistenceData data) {
checkObj(data, "PersistenceData");
checkObj(data.getVersion(), "version");
String dataInfoId = DataInfo.toDataInfoId(data.getDataId(), data.getInstanceId(),
data.getGroup());
try {
boolean ret = persistenceDataDBService.remove(dataInfoId);
DB_LOGGER.info("remove Persistence Data {} from DB result {}!", data, ret);
} catch (Exception e) {
DB_LOGGER.error("error remove Persistence Data {} from DB!", data);
throw new RuntimeException("Remove Persistence Data " + data + " from DB error!");
}
fireDataChangeNotify(data.getVersion(), dataInfoId, DataOperator.REMOVE);
Result result = new Result();
result.setSuccess(true);
return result;
}
@Path("/post")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response createCamel(String species) throws Exception {
Map<String, Object> params = new HashMap<>();
params.put("species", species);
producerTemplate.requestBodyAndHeaders(
"sql:INSERT INTO camel (species) VALUES (:#species)", null,
params);
return Response
.created(new URI("https://camel.apache.org/"))
.build();
}
/**
* <p>Disables the specified plugins from usage for customer account associated with the current user.</p>
*
* @param pluginIds a list of IDs of plugins to be disabled.
* @return empty response.
*/
@POST
@Path("/private/disabled")
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public Response saveUsedPlugins(Integer[] pluginIds) {
try {
if (!SecurityContext.get().hasPermission("plugins_customer_access_management")) {
logger.error("The user is not granted the 'plugins_customer_access_management' permission");
return Response.PERMISSION_DENIED();
}
this.pluginDAO.saveDisabledPlugins(pluginIds);
this.pluginStatusCache.setCustomerDisabledPlugins(SecurityContext.get().getCurrentUser().get().getCustomerId(), pluginIds);
return Response.OK();
} catch (Exception e) {
logger.error("Unexpected error when disabling plugins", e);
return Response.INTERNAL_ERROR();
}
}
@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();
}
@POST
@Path("/query")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
@Produces(MediaType.TEXT_HTML)
public Viewable submitQuery(@FormParam("query") String query,
@FormParam("queryType") String queryType,
@FormParam("autoLimit") String autoLimit) throws Exception {
try {
final String trimmedQueryString = CharMatcher.is(';').trimTrailingFrom(query.trim());
final QueryResult result = submitQueryJSON(new QueryWrapper(trimmedQueryString, queryType, autoLimit));
List<Integer> rowsPerPageValues = work.getContext().getConfig().getIntList(ExecConstants.HTTP_WEB_CLIENT_RESULTSET_ROWS_PER_PAGE_VALUES);
Collections.sort(rowsPerPageValues);
final String rowsPerPageValuesAsStr = Joiner.on(",").join(rowsPerPageValues);
return ViewableWithPermissions.create(authEnabled.get(), "/rest/query/result.ftl", sc, new TabularResult(result, rowsPerPageValuesAsStr));
} catch (Exception | Error e) {
logger.error("Query from Web UI Failed: {}", e);
return ViewableWithPermissions.create(authEnabled.get(), "/rest/errorMessage.ftl", sc, e);
}
}
/**
* <p>Gets the list of device log records matching the specified filter.</p>
*
* @param filter a filter to be used for filtering the records.
* @return a response with list of device log records matching the specified filter.
*/
@ApiOperation(
value = "Search logs",
notes = "Gets the list of log records matching the specified filter",
response = PaginatedData.class,
authorizations = {@Authorization("Bearer Token")}
)
@POST
@Path("/private/search")
@Produces(MediaType.APPLICATION_JSON)
public Response getLogs(DeviceLogFilter filter) {
try {
List<DeviceLogRecord> records = this.deviceLogDAO.findAll(filter);
long count = this.deviceLogDAO.countAll(filter);
return Response.OK(new PaginatedData<>(records, count));
} catch (Exception e) {
logger.error("Failed to search the log records due to unexpected error. Filter: {}", filter, e);
return Response.INTERNAL_ERROR();
}
}
/**
* <p>Gets the list of audit log records matching the specified filter.</p>
*
* @param filter a filter to be used for filtering the records.
* @return a response with list of audit log records matching the specified filter.
*/
@ApiOperation(
value = "Search logs",
notes = "Gets the list of audit log records matching the specified filter",
response = PaginatedData.class,
authorizations = {@Authorization("Bearer Token")}
)
@POST
@Path("/private/log/search")
@Produces(MediaType.APPLICATION_JSON)
public Response getLogs(AuditLogFilter filter) {
try {
List<AuditLogRecord> records = this.auditDAO.findAll(filter);
long count = this.auditDAO.countAll(filter);
return Response.OK(new PaginatedData<>(records, count));
} catch (Exception e) {
logger.error("Failed to search the audit log records due to unexpected error. Filter: {}", filter, e);
return Response.INTERNAL_ERROR();
}
}
@POST
@Path("discover/{provider}")
public CloudAccount discover(@PathParam("provider") String provider) {
provider = sanitize(provider);
var account = this.service.discover(provider);
if (account == null) {
throw new NotFoundException();
}
return account;
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
@Path("{id}/disable")
public void disable(@PathParam("id") String id) {
id = sanitize(id);
var scan = service.getScan(id);
if (scan == null) {
LOGGER.error("Could not find scan with id {}", id);
throw new NotFoundException("Could not find scan with id " + id);
}
service.disableScan(scan);
}
@POST
@Path("import/{certificationId}")
public void importCertification(@PathParam("certificationId") String certificationId) {
certificationId = sanitize(certificationId);
var certification = this.service.load(certificationId);
if (certification == null) {
throw new NotFoundException();
}
this.service.modifyCertification(certification);
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
@Path("/{personId}")
public void updatePerson(@PathParam("personId") long id, @Valid Person p) {
Person toUpdate = getPerson(id);
if (toUpdate == null)
personNotFound(id);
personRepo.put(id, p);
}
@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-r5", patient, InputStream.class)) {
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response)
.build();
}
}
@Path("/unmarshal-lastname")
@POST
@Consumes(MediaType.APPLICATION_XML)
@Produces(MediaType.TEXT_PLAIN)
public Response unmarshalLastNameFromXml(String message) throws Exception {
LOG.infof("Sending to jaxb: %s", message);
final Person response = producerTemplate.requestBody("direct:unmarshal", message, Person.class);
LOG.infof("Got response from jaxb: %s", response);
return Response
.created(new URI("https://camel.apache.org/"))
.entity(response.getLastName())
.build();
}
@SuppressWarnings("unchecked")
@Path("/csv-to-json")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public List<List<Object>> csv2json(String csv) throws Exception {
return producerTemplate.requestBody("direct:csv-to-json", csv, List.class);
}
@POST
@Path("/gracefulShutdown")
@Produces(MediaType.APPLICATION_JSON)
@RolesAllowed(ADMIN_ROLE)
public Response shutdownDrillbit() throws Exception {
String resp = "Graceful Shutdown request is triggered";
return shutdown(resp);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
public Result changeDecisionMode(DecisionMode decisionMode) {
((MetaServerConfigBean) metaServerConfig).setDecisionMode(decisionMode);
Result result = new Result();
result.setSuccess(true);
return result;
}
@Path("/templateFromHeader")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public String templateFromHeader(String message) {
LOG.infof("Calling templateFromHeader with %s", message);
return template.requestBodyAndHeader("mustache://template/simple.mustache?allowTemplateFromHeader=true", message,
MustacheConstants.MUSTACHE_TEMPLATE,
"Body='{{body}}'", String.class);
}
@POST
@Path("/selective")
@SubmarineApi
public Response selectByPrimaryKeySelective(Metric metric) {
List<Metric> metrics;
try {
metrics = metricService.selectByPrimaryKeySelective(metric);
} catch (Exception e) {
LOG.error(e.toString());
return new JsonResponse.Builder<Boolean>(Response.Status.OK).success(false).build();
}
return new JsonResponse.Builder<List<Metric>>(Response.Status.OK).success(true).result(metrics).build();
}
@POST
@Path("/add")
@SubmarineApi
public Response postParam(Param param) {
LOG.info("postParam ({})", param);
boolean result = false;
try {
result = paramService.insert(param);
} catch (Exception e) {
LOG.error(e.toString());
return new JsonResponse.Builder<Boolean>(Response.Status.OK).success(false).build();
}
return new JsonResponse.Builder<Boolean>(Response.Status.OK).success(true).result(result).build();
}
@Path("/media")
@POST
@Produces(MediaType.TEXT_PLAIN)
public Response postMedia(@HeaderParam("Content-type") String type, byte[] message) throws Exception {
final TelegramMediaType telegramMediaType;
if (type != null && type.startsWith("image/")) {
telegramMediaType = TelegramMediaType.PHOTO_PNG;
} else if (type != null && type.startsWith("audio/")) {
telegramMediaType = TelegramMediaType.AUDIO;
} else if (type != null && type.startsWith("video/")) {
telegramMediaType = TelegramMediaType.VIDEO;
} else if (type != null && type.startsWith("application/pdf")) {
telegramMediaType = TelegramMediaType.DOCUMENT;
} else {
return Response.status(415, "Unsupported content type " + type).build();
}
producerTemplate.requestBodyAndHeader(
String.format("telegram://bots?chatId=%s", chatId),
message,
TelegramConstants.TELEGRAM_MEDIA_TYPE,
telegramMediaType);
log.infof("Sent a message to telegram %s", message);
return Response
.created(new URI(String.format("https://telegram.org/")))
.build();
}
@Path("/post")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.TEXT_PLAIN)
public Response post(String message) throws Exception {
String result = producerTemplate.requestBody("direct:start", message, String.class);
return Response.created(new URI("https://camel.apache.org/")).entity(result).build();
}
@POST
public CompletionStage<Beverage> process(Order order) {
return CompletableFuture.supplyAsync(() -> {
Beverage coffee = prepare(order);
LOGGER.info("Order {} for {} is ready", order.getProduct(), order.getName());
return coffee;
}, queue);
}
@Path("/createFromText")
@POST
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response createFromText(String message) throws Exception {
document = producerTemplate.requestBody(
"pdf:create?fontSize=6&pageSize=PAGE_SIZE_A5&font=Courier", message, byte[].class);
LOG.infof("The PDDocument has been created and contains %d bytes", document.length);
return Response.created(new URI("pdf/extractText")).entity(document).build();
}
@POST
public Long createPerson(@QueryParam("name") @NotEmpty @Size(min = 2, max = 50) String name,
@QueryParam("age") @PositiveOrZero int age) {
Person p = new Person(name, age);
personRepo.put(p.id, p);
return p.id;
}
@POST
@Path("/2step-code")
@SubmarineApi
public Response step() {
String data = "{stepCode:1}";
return new JsonResponse.Builder<String>(Response.Status.OK).success(true).result(data).build();
}