下面列出了怎么用javax.ws.rs.DELETE的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Returns the experiment that deleted
* @param id experiment id
* @return the detailed info about deleted experiment
*/
@DELETE
@Path("/{id}")
@Operation(summary = "Delete the experiment",
tags = {"experiment"},
responses = {
@ApiResponse(description = "successful operation", content = @Content(
schema = @Schema(implementation = JsonResponse.class))),
@ApiResponse(responseCode = "404", description = "Experiment not found")})
public Response deleteExperiment(@PathParam(RestConstants.ID) String id) {
try {
Experiment experiment = experimentManager.deleteExperiment(id);
return new JsonResponse.Builder<Experiment>(Response.Status.OK).success(true)
.result(experiment).build();
} catch (SubmarineRuntimeException e) {
return parseExperimentServiceException(e);
}
}
@DELETE
@Path("/deleteBatch")
@SubmarineApi
public Response deleteBatch(@QueryParam("ids") String ids) {
LOG.info("deleteBatch({})", ids.toString());
try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
SysDeptMapper sysDeptMapper = sqlSession.getMapper(SysDeptMapper.class);
sysDeptMapper.deleteBatch(Arrays.asList(ids.split(",")));
sqlSession.commit();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK)
.message("Batch delete department failed!").success(false).build();
}
return new JsonResponse.Builder<>(Response.Status.OK)
.message("Batch delete department successfully!").success(true).build();
}
@DELETE
@Path("/remove")
@SubmarineApi
public Response remove(String id) {
LOG.info("remove({})", id);
try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
SysDeptMapper sysDeptMapper = sqlSession.getMapper(SysDeptMapper.class);
sysDeptMapper.deleteById(id);
sqlSession.commit();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK)
.message("Delete department failed!").success(false).build();
}
return new JsonResponse.Builder<>(Response.Status.OK)
.message("Delete department successfully!").success(true).build();
}
@DELETE
@Path("/delete")
@SubmarineApi
public Response delete(@QueryParam("id") String id) {
// TODO(zhulinhao): At the front desk need to id
LOG.info("delete team:{}", id);
// Delete data in a team and team_member table
// TODO(zhulinhao):delete sys_message's invite messages
try {
teamService.delete(id);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK).success(false)
.message("delete team failed!").build();
}
return new JsonResponse.Builder<>(Response.Status.OK)
.message("Delete team successfully!").success(true).build();
}
@DELETE
@Path("/delete")
@SubmarineApi
public Response delete(@QueryParam("id") String id) {
// TODO(zhulinhao): At the front desk need to id
LOG.info("delete project:{}", id);
try {
projectService.delete(id);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK).success(false)
.message("Delete project failed!").build();
}
return new JsonResponse.Builder<>(Response.Status.OK)
.message("Delete project successfully!").success(true).build();
}
@DELETE
@Path("/delete")
@SubmarineApi
public Response delete(@QueryParam("id") String id) {
LOG.info("delete({})", id);
try {
userService.delete(id);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK).success(false)
.message("delete user failed!").build();
}
return new JsonResponse.Builder<>(Response.Status.OK)
.success(true).message("delete user successfully!").build();
}
/**
* Rest endpoint to delete specific bucket.
* <p>
* See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketDELETE.html
* for more details.
*/
@DELETE
public Response delete(@PathParam("bucket") String bucketName)
throws IOException, OS3Exception {
try {
deleteS3Bucket(bucketName);
} catch (OMException ex) {
if (ex.getResult() == ResultCodes.BUCKET_NOT_EMPTY) {
throw S3ErrorTable.newError(S3ErrorTable
.BUCKET_NOT_EMPTY, bucketName);
} else if (ex.getResult() == ResultCodes.BUCKET_NOT_FOUND) {
throw S3ErrorTable.newError(S3ErrorTable
.NO_SUCH_BUCKET, bucketName);
} else {
throw ex;
}
}
return Response
.status(HttpStatus.SC_NO_CONTENT)
.build();
}
@DELETE
@Path("/customers/{id}/")
public Response deleteCustomer(@PathParam("id") String id) {
System.out.println("----invoking deleteCustomer, Customer id is: " + id);
long idNumber = Long.parseLong(id);
Customer c = customers.get(idNumber);
Response r;
if (c != null) {
r = Response.ok().build();
customers.remove(idNumber);
} else {
r = Response.notModified().build();
}
return r;
}
@ResourceSecurity(INTERNAL_ONLY)
@DELETE
@Path("{taskId}")
@Produces(MediaType.APPLICATION_JSON)
public TaskInfo deleteTask(
@PathParam("taskId") TaskId taskId,
@QueryParam("abort") @DefaultValue("true") boolean abort,
@Context UriInfo uriInfo)
{
requireNonNull(taskId, "taskId is null");
TaskInfo taskInfo;
if (abort) {
taskInfo = taskManager.abortTask(taskId);
}
else {
taskInfo = taskManager.cancelTask(taskId);
}
if (shouldSummarize(uriInfo)) {
taskInfo = taskInfo.summarize();
}
return taskInfo;
}
@ResourceSecurity(AUTHENTICATED_USER)
@DELETE
@Path("{queryId}")
public void cancelQuery(@PathParam("queryId") QueryId queryId, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
requireNonNull(queryId, "queryId is null");
try {
BasicQueryInfo queryInfo = dispatchManager.getQueryInfo(queryId);
checkCanKillQueryOwnedBy(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queryInfo.getSession().getUser(), accessControl);
dispatchManager.cancelQuery(queryId);
}
catch (AccessDeniedException e) {
throw new ForbiddenException();
}
catch (NoSuchElementException ignored) {
}
}
@DELETE
@Path("{uuid}")
public synchronized Response deleteRequest(
@HeaderParam(PRESTO_ENVIRONMENT) String environment,
@PathParam("uuid") UUID uuid)
{
checkEnvironment(environment);
if (!shards.containsKey(uuid)) {
return Response.status(NOT_FOUND).build();
}
if (shards.get(uuid) == null) {
return Response.status(GONE).build();
}
shards.put(uuid, null);
return Response.noContent().build();
}
@DELETE
@Path("/v1/proxy")
@Produces(APPLICATION_JSON)
public void cancelQuery(
@QueryParam("uri") String uri,
@QueryParam("hmac") String hash,
@Context HttpServletRequest servletRequest,
@Suspended AsyncResponse asyncResponse)
{
if (!hmac.hashString(uri, UTF_8).equals(HashCode.fromString(hash))) {
throw badRequest(FORBIDDEN, "Failed to validate HMAC of URI");
}
Request.Builder request = prepareDelete().setUri(URI.create(uri));
performRequest(servletRequest, asyncResponse, request, response -> responseWithHeaders(noContent(), response));
}
@ApiOperation(
value = "Delete device",
notes = "Delete an existing device"
)
@DELETE
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public Response removeDevice(@PathParam("id") @ApiParam("Device ID") Integer id) {
final boolean canEditDevices = SecurityContext.get().hasPermission("edit_devices");
if (!(canEditDevices)) {
log.error("Unauthorized attempt to delete device",
SecurityException.onCustomerDataAccessViolation(id, "device"));
return Response.PERMISSION_DENIED();
}
this.deviceDAO.removeDeviceById(id);
return Response.OK();
}
@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());
}
}
@DELETE
@Path("/{namespace}/{set}")
@Operation(summary = "Delete entries in a set between provided weights")
@ApiResponses(value = {
@ApiResponse(responseCode = "200", description = "Successfully deleted entries between and including provided weights"),
@ApiResponse(responseCode = "400", description = "One of the query parameters has a bad value"),
@ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response delete(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
@Parameter(description = "Name of the set") @PathParam("set") final String set,
@Parameter(description = "Minimum weight for an entry", example = "0") @QueryParam("min") final long min,
@Parameter(description = "Maximum weight for an entry", example = "0") @QueryParam("max") final long max) throws IOException {
logger.info("received request to delete entries in set/namespace {}/{} between weights {}-{}", set, namespace, min, max);
this.cantor.sets().delete(namespace, set, min, max);
return Response.ok().build();
}
@DELETE
@Path("/{namespace}/{set}/{entry}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Delete a specific entry by name")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",
description = "Provides single property json with a boolean which is only true if the key was found and the entry was deleted",
content = @Content(schema = @Schema(implementation = HttpModels.DeleteResponse.class))),
@ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response delete(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
@Parameter(description = "Name of the set") @PathParam("set") final String set,
@Parameter(description = "Name of the entry") @PathParam("entry") final String entry) throws IOException {
logger.info("received request to delete entry {} in set/namespace {}/{}", entry, set, namespace);
final Map<String, Boolean> completed = new HashMap<>();
completed.put(jsonFieldResults, this.cantor.sets().delete(namespace, set, entry));
return Response.ok(parser.toJson(completed)).build();
}
@DELETE
@Path("/pop/{namespace}/{set}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Pop entries from a set")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",
description = "Entries and weights of elements popped matching query parameters",
content = @Content(schema = @Schema(implementation = Map.class))),
@ApiResponse(responseCode = "400", description = "One of the query parameters has a bad value"),
@ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response pop(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
@Parameter(description = "Name of the set") @PathParam("set") final String set,
@BeanParam final SetsDataSourceBean bean) throws IOException {
logger.info("received request to pop off set/namespace {}/{}", set, namespace);
logger.debug("request parameters: {}", bean);
final Map<String, Long> entries = this.cantor.sets().pop(
namespace,
set,
bean.getMin(),
bean.getMax(),
bean.getStart(),
bean.getCount(),
bean.isAscending());
return Response.ok(parser.toJson(entries)).build();
}
@DELETE
@Path("/delete/{namespace}")
@Operation(summary = "Delete events")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",
description = "All specified events were deleted",
content = @Content(schema = @Schema(implementation = HttpModels.CountResponse.class))),
@ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response dropEvents(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
@BeanParam final EventsDataSourceBean bean) throws IOException {
logger.info("received request to drop namespace {}", namespace);
final int eventsDeleted = this.cantor.events().delete(
namespace,
bean.getStart(),
bean.getEnd(),
bean.getMetadataQuery(),
bean.getDimensionQuery());
final Map<String, Integer> countResponse = new HashMap<>();
countResponse.put(jsonFieldCount, eventsDeleted);
return Response.ok(parser.toJson(countResponse)).build();
}
@DELETE
@Path("/{namespace}/{key}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Delete an object by its key")
@ApiResponses(value = {
@ApiResponse(responseCode = "200",
description = "Provides single property json with a boolean which is only true if the key was found and the object was deleted",
content = @Content(schema = @Schema(implementation = HttpModels.DeleteResponse.class))),
@ApiResponse(responseCode = "500", description = serverErrorMessage)
})
public Response deleteByKey(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
@Parameter(description = "Key of the object") @PathParam("key") final String key) throws IOException {
logger.info("received request to delete object '{}' in namespace {}", key, namespace);
final Map<String, Boolean> completed = new HashMap<>();
completed.put(jsonFieldResults, this.cantor.objects().delete(namespace, key));
return Response.ok(parser.toJson(completed)).build();
}
@DELETE()
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public $Type$Output deleteResource_$name$(@PathParam("id") final String id) {
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.abort();
return getModel(pi);
}
});
}
@DELETE()
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public CompletionStage<$Type$Output> deleteResource_$name$(@PathParam("id") final String id) {
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.abort();
return getModel(pi);
}
});
});
}
@DELETE
@Consumes(MediaType.APPLICATION_JSON)
@Path("{id}")
public void deleteUser(@PathParam("id") String id) {
id = sanitize(id);
this.service.deleteUser(id);
}
@DELETE
@Path("/schemas/{schemaid}")
@Produces({"application/json"})
public Response apiSchemasSchemaidDelete(@PathParam("schemaid") String schemaid)
throws ArtifactNotFoundException {
return service.apiSchemasSchemaidDelete(schemaid);
}
@DELETE
@Path("/schemas/{schemaid}/versions/{versionnum}")
@Produces({"application/json"})
public Response apiSchemasSchemaidVersionsVersionnumDelete(@PathParam("schemaid") String schemaid, @PathParam("versionnum") int versionnum)
throws ArtifactNotFoundException {
return service.apiSchemasSchemaidVersionsVersionnumDelete(schemaid, versionnum);
}
@DELETE
@Path("/delete")
@SubmarineApi
public Response deleteMetric(@QueryParam("id") String id) {
boolean result = false;
try {
result = metricService.deleteById(id);
} 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();
}
@DELETE
@Path("/delete")
@SubmarineApi
public Response deleteParam(@QueryParam("id") String id) {
LOG.info("deleteParam ({})", id);
boolean result = false;
try {
result = paramService.deleteById(id);
} 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();
}
@DELETE
@Path("/delete")
@SubmarineApi
public Response delete(@QueryParam("id") String id, @QueryParam("deleted") int deleted) {
LOG.info("delete({}, {})", id, deleted);
String msgOperation = "Delete";
if (deleted == 0) {
msgOperation = "Restore";
}
try (SqlSession sqlSession = MyBatisUtil.getSqlSession()) {
SysDeptMapper sysDeptMapper = sqlSession.getMapper(SysDeptMapper.class);
SysDept dept = new SysDept();
dept.setId(id);
dept.setDeleted(deleted);
sysDeptMapper.updateBy(dept);
sqlSession.commit();
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return new JsonResponse.Builder<>(Response.Status.OK)
.message(msgOperation + " department failed!").success(false).build();
}
return new JsonResponse.Builder<>(Response.Status.OK)
.message(msgOperation + " department successfully!").success(true).build();
}
@DELETE
@Path("/{pid}")
@Produces({"application/json"})
public Response deleteFidoPolicy(@PathParam("did") Long did,
@PathParam("pid") String pid) {
if (!authRest.execute(did, request, null)) {
return Response.status(Response.Status.UNAUTHORIZED).build();
}
return deletepolicybean.execute(did, pid);
}
/**
* Delete a specific object from a bucket, if query param uploadId is
* specified, this request is for abort multipart upload.
* <p>
* See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectDELETE.html
* https://docs.aws.amazon.com/AmazonS3/latest/API/mpUploadAbort.html
* for more details.
*/
@DELETE
@SuppressWarnings("emptyblock")
public Response delete(
@PathParam("bucket") String bucketName,
@PathParam("path") String keyPath,
@QueryParam("uploadId") @DefaultValue("") String uploadId) throws
IOException, OS3Exception {
try {
if (uploadId != null && !uploadId.equals("")) {
return abortMultipartUpload(bucketName, keyPath, uploadId);
}
OzoneBucket bucket = getBucket(bucketName);
bucket.getKey(keyPath);
bucket.deleteKey(keyPath);
} catch (OMException ex) {
if (ex.getResult() == ResultCodes.BUCKET_NOT_FOUND) {
throw S3ErrorTable.newError(S3ErrorTable
.NO_SUCH_BUCKET, bucketName);
} else if (ex.getResult() == ResultCodes.KEY_NOT_FOUND) {
//NOT_FOUND is not a problem, AWS doesn't throw exception for missing
// keys. Just return 204
} else {
throw ex;
}
}
return Response
.status(Status.NO_CONTENT)
.build();
}
@Override
public void initMethodAnnotationProcessor() {
super.initMethodAnnotationProcessor();
methodAnnotationMap.put(Path.class, new PathMethodAnnotationProcessor());
HttpMethodAnnotationProcessor httpMethodAnnotationProcessor = new HttpMethodAnnotationProcessor();
methodAnnotationMap.put(GET.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(POST.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(DELETE.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(PATCH.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(PUT.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(OPTIONS.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(HEAD.class, httpMethodAnnotationProcessor);
methodAnnotationMap.put(Consumes.class, new ConsumesAnnotationProcessor());
}