下面列出了怎么用javax.ws.rs.HEAD的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* Rest endpoint to check the existence of a bucket.
* <p>
* See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTBucketHEAD.html
* for more details.
*/
@HEAD
public Response head(@PathParam("bucket") String bucketName)
throws OS3Exception, IOException {
try {
getBucket(bucketName);
} catch (OS3Exception ex) {
LOG.error("Exception occurred in headBucket", ex);
//TODO: use a subclass fo OS3Exception and catch it here.
if (ex.getCode().contains("NoSuchBucket")) {
return Response.status(Status.BAD_REQUEST).build();
} else {
throw ex;
}
}
return Response.ok().build();
}
@HEAD
@Path("/token/openshift")
public Response openShiftTokenExists(@HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization,
@QueryParam("cluster") String cluster) {
boolean tokenExists;
try {
tokenExists = getOpenShiftIdentity(authorization, cluster) != null;
} catch (IllegalArgumentException | IllegalStateException e) {
tokenExists = false;
}
if (tokenExists) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@Test
public void testHttpHead() throws Exception {
HttpProcessorConfig conf = new HttpProcessorConfig();
conf.httpMethod = HttpMethod.HEAD;
conf.dataFormat = DataFormat.TEXT;
conf.resourceUrl = getBaseUri() + "test/head";
conf.headerOutputLocation = HeaderOutputLocation.HEADER;
List<Record> records = createRecords("test/head");
ProcessorRunner runner = createProcessorRunner(conf);
try {
StageRunner.Output output = runner.runProcess(records);
getOutputField(output);
Record.Header header = getOutputRecord(output).getHeader();
assertEquals("StreamSets", header.getAttribute("x-test-header"));
assertEquals("[a, b]", header.getAttribute("x-list-header"));
} finally {
runner.runDestroy();
}
}
@Path("attributes-{attributes}/{consumer-id}")
@HEAD
public Response headConsumer(@PathParam("attributes") int attributes,
@PathParam("consumer-id") String consumerId,
@Context UriInfo uriInfo) throws Exception {
ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\"");
QueueConsumer consumer = findConsumer(attributes, consumerId, uriInfo);
Response.ResponseBuilder builder = Response.noContent();
// we synchronize just in case a failed request is still processing
synchronized (consumer) {
if ((attributes & ACKNOWLEDGED) > 0) {
AcknowledgedQueueConsumer ackedConsumer = (AcknowledgedQueueConsumer) consumer;
Acknowledgement ack = ackedConsumer.getAck();
if (ack == null || ack.wasSet()) {
AcknowledgedQueueConsumer.setAcknowledgeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId(), Long.toString(consumer.getConsumeIndex()));
} else {
ackedConsumer.setAcknowledgementLink(builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId());
}
} else {
QueueConsumer.setConsumeNextLink(serviceManager.getLinkStrategy(), builder, uriInfo, uriInfo.getMatchedURIs().get(1) + "/attributes-" + attributes + "/" + consumer.getId(), Long.toString(consumer.getConsumeIndex()));
}
}
return builder.build();
}
@HEAD
@Path("/{username}")
@ApiOperation(value = "Testing an user existence")
@ApiImplicitParams({
@ApiImplicitParam(required = true, dataType = "string", name = "username", paramType = "path")
})
@ApiResponses(value = {
@ApiResponse(code = HttpStatus.OK_200, message = "OK. User exists."),
@ApiResponse(code = HttpStatus.BAD_REQUEST_400, message = "Invalid input user."),
@ApiResponse(code = HttpStatus.NOT_FOUND_404, message = "User does not exist."),
@ApiResponse(code = HttpStatus.INTERNAL_SERVER_ERROR_500,
message = "Internal server error - Something went bad on the server side.")
})
public void defineUserExist() {
service.head(USERS + SEPARATOR + USER_NAME, this::userExist);
}
/**
* Rest endpoint to check existence of an object in a bucket.
* <p>
* See: https://docs.aws.amazon.com/AmazonS3/latest/API/RESTObjectHEAD.html
* for more details.
*/
@HEAD
public Response head(
@PathParam("bucket") String bucketName,
@PathParam("path") String keyPath) throws IOException, OS3Exception {
OzoneKeyDetails key;
try {
key = getBucket(bucketName).getKey(keyPath);
// TODO: return the specified range bytes of this object.
} catch (OMException ex) {
if (ex.getResult() == ResultCodes.KEY_NOT_FOUND) {
// Just return 404 with no content
return Response.status(Status.NOT_FOUND).build();
} else {
throw ex;
}
}
ResponseBuilder response = Response.ok().status(HttpStatus.SC_OK)
.header("ETag", "" + key.getModificationTime())
.header("Content-Length", key.getDataSize())
.header("Content-Type", "binary/octet-stream");
addLastModifiedDate(response, key);
return response.build();
}
@Produces({ MediaType.APPLICATION_JSON })
@Path("/{email}")
@HEAD
public Response checkPerson(@PathParam("email") final String email) {
if (peopleService.checkPersonByEmail(email)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).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());
}
@ResourceSecurity(PUBLIC)
@HEAD
@Produces(APPLICATION_JSON) // to match the GET route
public Response statusPing()
{
return Response.ok().build();
}
@HEAD
@Path("{uuid}")
public synchronized Response headRequest(
@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();
}
return Response.noContent().build();
}
@HEAD
@Path("{familyId}")
public void reload(@PathParam("familyId") final String familyId) {
final ComponentFamilyMeta family = ofNullable(componentFamilyDao.findById(familyId))
.orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
service
.manager()
.findPlugin(family.getPlugin())
.orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND))
.get(ContainerManager.Actions.class)
.reload();
log.info("Reloaded family {}", family.getName());
}
@HEAD
@Produces({ MediaType.APPLICATION_JSON })
@Path("{listEntryId}/ecrfpdf/{ecrfId}")
public ECRFPDFVO renderEcrfHead(@PathParam("listEntryId") Long listEntryId, @PathParam("ecrfId") Long ecrfId,
@QueryParam("blank") Boolean blank) throws AuthenticationException, AuthorisationException, ServiceException {
ECRFPDFVO result = WebUtil.getServiceLocator().getTrialService().renderEcrf(auth, ecrfId, null, listEntryId, blank);
result.setDocumentDatas(null);
return result;
}
@HEAD
@Produces({ MediaType.APPLICATION_JSON })
@Path("{listEntryId}/ecrfpdf")
public ECRFPDFVO renderEcrfsHead(@PathParam("listEntryId") Long listEntryId,
@QueryParam("blank") Boolean blank) throws AuthenticationException, AuthorisationException, ServiceException {
ECRFPDFVO result = WebUtil.getServiceLocator().getTrialService().renderEcrfs(auth, null, listEntryId, null, blank);
result.setDocumentDatas(null);
return result;
}
@HEAD
@Produces({ MediaType.APPLICATION_JSON })
@Path("{id}/probandletterpdf")
public ProbandLetterPDFVO renderProbandLetterPDFHead(@PathParam("id") Long id)
throws AuthenticationException, AuthorisationException, ServiceException {
ProbandLetterPDFVO result = WebUtil.getServiceLocator().getProbandService().renderProbandLetterPDF(auth, id);
result.setDocumentDatas(null);
return result;
}
@HEAD
@Path("test:table/blob1")
public Response getBlobMetadata(@HeaderParam("X-BV-API-Key") String apiKey) {
assertEquals(apiKey, API_KEY);
return Response.ok()
.type(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_LENGTH, 12)
.header(HttpHeaders.ETAG, "etag")
.header("X-BV-Length", 12)
.header("X-BVA-size", "medium")
.lastModified(new Date(1444937753000L))
.build();
}
/**
* Retrieve metainformation about the entity implied by the request.
* curl -i -X HEAD http://localhost:9090/stockquote/IBM
*
* @return Response
*/
@HEAD
@Path("/{symbol}")
@Produces({"application/json", "text/xml"})
@ApiOperation(
value = "Returns headers of corresponding GET request ",
notes = "Returns metainformation contained in the HTTP header identical to the corresponding GET Request")
public Response getMetaInformationForQuote(@ApiParam(value = "Symbol", required = true)
@PathParam("symbol") String symbol) throws SymbolNotFoundException {
Stock stock = stockQuotes.get(symbol);
if (stock == null) {
throw new SymbolNotFoundException();
}
return Response.ok().build();
}
@HEAD
@Path("/repository/{repo}")
public Response repositoryExists(@HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization,
@NotNull @PathParam("repo") String repository) {
Identity githubIdentity = getGitHubIdentity(authorization);
GitHubService gitHubService = gitHubServiceFactory.create(githubIdentity);
if (gitHubService.repositoryExists(gitHubService.getLoggedUser().getLogin() + "/" + repository)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@HEAD
@Path("/project/{project}")
public Response projectExists(@HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization,
@NotNull @PathParam("project") String project,
@QueryParam("cluster") String cluster) {
Identity openShiftIdentity = getOpenShiftIdentity(authorization, cluster);
Optional<OpenShiftCluster> openShiftCluster = clusterRegistry.findClusterById(cluster);
assert openShiftCluster.isPresent() : "Cluster not found: " + cluster;
OpenShiftService openShiftService = openShiftServiceFactory.create(openShiftCluster.get(), openShiftIdentity);
if (openShiftService.projectExists(project)) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@HEAD
@Path("/token/github")
public Response gitHubTokenExists(@HeaderParam(HttpHeaders.AUTHORIZATION) final String authorization) {
boolean tokenExists;
try {
tokenExists = getGitHubIdentity(authorization) != null;
} catch (IllegalArgumentException | IllegalStateException e) {
tokenExists = false;
}
if (tokenExists) {
return Response.ok().build();
} else {
return Response.status(Response.Status.NOT_FOUND).build();
}
}
@HEAD
public Response head(@Context UriInfo uriInfo)
{
UriBuilder absolute = uriInfo.getBaseUriBuilder();
URI customerUrl = absolute.clone().path(CustomerResource.class).build();
URI orderUrl = absolute.clone().path(OrderResource.class).build();
Response.ResponseBuilder builder = Response.ok();
Link customers = Link.fromUri(customerUrl).rel("customers").type("application/xml").build();
Link orders = Link.fromUri(orderUrl).rel("orders").type("application/xml").build();
builder.links(customers, orders);
return builder.build();
}
@HEAD
@Path("{id}")
@Produces("application/xml")
public Response getOrderHeaders(@PathParam("id") int id, @Context UriInfo uriInfo)
{
Order order = orderDB.get(id);
if (order == null)
{
throw new WebApplicationException(Response.Status.NOT_FOUND);
}
Response.ResponseBuilder builder = Response.ok();
builder.type("application/xml");
if (!order.isCancelled()) addCancelHeader(uriInfo, builder);
return builder.build();
}
@HEAD
@Produces("application/xml")
public Response getOrdersHeaders(@QueryParam("start") int start,
@QueryParam("size") @DefaultValue("2") int size,
@Context UriInfo uriInfo)
{
Response.ResponseBuilder builder = Response.ok();
builder.type("application/xml");
addPurgeLinkHeader(uriInfo, builder);
return builder.build();
}
@HEAD
public Response headPing() {
LOG.debug("ping called");
return healthCheck.execute().isHealthy()
? Response.noContent().build()
: Response.serverError().build();
}
@RolesAllowed("ADMIN")
@HEAD
@Path("/{resource}{action:(/[^/]+?)?}{id:(/[^/]+?)?}")
public Response headCommand(@PathParam("param") String command) {
// Just an Empty response
return Response.status(200).build();
}
/**
* Retrieve metainformation about the entity implied by the request.
* curl -i -X HEAD http://localhost:8080/stockquote/IBM
*
* @return Response
*/
@HEAD
@Path("/{symbol}")
@Produces({"application/json", "text/xml"})
@ApiOperation(
value = "Returns headers of corresponding GET request ",
notes = "Returns metainformation contained in the HTTP header identical to the corresponding GET Request")
public Response getMetaInformationForQuote(@ApiParam(value = "Symbol", required = true)
@PathParam("symbol") String symbol) throws SymbolNotFoundException {
Stock stock = stockQuotes.get(symbol);
if (stock == null) {
throw new SymbolNotFoundException();
}
return Response.ok().build();
}
/**
* Retrieve metainformation about the entity implied by the request.
* curl -i -X HEAD http://localhost:8080/stockquote/IBM
*
* @return Response
*/
@HEAD
@Path("/{symbol}")
@Produces({"application/json", "text/xml"})
@ApiOperation(
value = "Returns headers of corresponding GET request ",
notes = "Returns metainformation contained in the HTTP header identical to the corresponding GET Request")
public Response getMetaInformationForQuote(@ApiParam(value = "Symbol", required = true)
@PathParam("symbol") String symbol) throws SymbolNotFoundException {
Stock stock = stockQuotes.get(symbol);
if (stock == null) {
throw new SymbolNotFoundException();
}
return Response.ok().build();
}
/**
* Fetches the HttpMethod from annotations and returns String representation of HttpMethod.
* Return emptyString if not present.
*
* @param method Method handling the http request.
* @return String representation of HttpMethod from annotations or emptyString as a default.
*/
private Set<String> getHttpMethods(Method method) {
Set<String> httpMethods = new HashSet();
boolean isSubResourceLocator = true;
if (method.isAnnotationPresent(GET.class)) {
httpMethods.add(HttpMethod.GET);
isSubResourceLocator = false;
}
if (method.isAnnotationPresent(PUT.class)) {
httpMethods.add(HttpMethod.PUT);
isSubResourceLocator = false;
}
if (method.isAnnotationPresent(POST.class)) {
httpMethods.add(HttpMethod.POST);
isSubResourceLocator = false;
}
if (method.isAnnotationPresent(DELETE.class)) {
httpMethods.add(HttpMethod.DELETE);
isSubResourceLocator = false;
}
if (method.isAnnotationPresent(HEAD.class)) {
httpMethods.add(HttpMethod.HEAD);
isSubResourceLocator = false;
}
if (method.isAnnotationPresent(OPTIONS.class)) {
httpMethods.add(HttpMethod.OPTIONS);
isSubResourceLocator = false;
}
// If this is a sub resource locator need to add all the method designator
if (isSubResourceLocator) {
httpMethods.add(HttpMethod.GET);
httpMethods.add(HttpMethod.POST);
httpMethods.add(HttpMethod.PUT);
httpMethods.add(HttpMethod.DELETE);
httpMethods.add(HttpMethod.HEAD);
httpMethods.add(HttpMethod.OPTIONS);
}
return Collections.unmodifiableSet(httpMethods);
}
/**
* Check if http verb is available for the method.
*
* @param method
* @return
*/
public static boolean isHttpMethodAvailable(Method method) {
return method.isAnnotationPresent(GET.class) ||
method.isAnnotationPresent(PUT.class) ||
method.isAnnotationPresent(POST.class) ||
method.isAnnotationPresent(DELETE.class) ||
method.isAnnotationPresent(HEAD.class) ||
method.isAnnotationPresent(OPTIONS.class);
}
private boolean isHttpMethodAvailable(Method method) {
return method.isAnnotationPresent(GET.class) ||
method.isAnnotationPresent(PUT.class) ||
method.isAnnotationPresent(POST.class) ||
method.isAnnotationPresent(DELETE.class) ||
method.isAnnotationPresent(HEAD.class) ||
method.isAnnotationPresent(OPTIONS.class);
}
@Test
public void testStreamingHead() throws Exception {
// Validates that a HEAD request successfully gets headers and has exactly 1 record output with an empty body
HttpClientConfigBean conf = new HttpClientConfigBean();
conf.client.authType = AuthenticationType.NONE;
conf.httpMode = HttpClientMode.STREAMING;
conf.headers.put("abcdef", "ghijkl");
conf.resourceUrl = getBaseUri() + "headers";
conf.client.readTimeoutMillis = 1000;
conf.basic.maxBatchSize = 100;
conf.basic.maxWaitTime = 1000;
conf.pollingInterval = 1000;
conf.httpMethod = HttpMethod.HEAD;
conf.dataFormat = DataFormat.JSON;
conf.dataFormatConfig.jsonContent = JsonMode.MULTIPLE_OBJECTS;
HttpClientSource origin = new HttpClientSource(conf);
SourceRunner runner = new SourceRunner.Builder(HttpClientDSource.class, origin)
.addOutputLane("lane")
.build();
runner.runInit();
try {
List<Record> parsedRecords = getRecords(runner);
assertEquals(1, parsedRecords.size());
Map<String, String> lowerCasedKeys = getLowerCaseHeaders(parsedRecords.get(0));
assertEquals("StreamSets", lowerCasedKeys.get("x-test-header"));
assertEquals("[a, b]", lowerCasedKeys.get("x-list-header"));
} finally {
runner.runDestroy();
}
}