javax.ws.rs.HEAD Java Examples

The following examples show how to use javax.ws.rs.HEAD. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ConsumersResource.java    From activemq-artemis with Apache License 2.0 8 votes vote down vote up
@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();
}
 
Example #2
Source File: UserRoutes.java    From james-project with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: BucketEndpoint.java    From hadoop-ozone with Apache License 2.0 6 votes vote down vote up
/**
 * 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();
}
 
Example #4
Source File: HttpProcessorIT.java    From datacollector with Apache License 2.0 6 votes vote down vote up
@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();
  }
}
 
Example #5
Source File: ValidationResource.java    From launchpad-missioncontrol with Apache License 2.0 6 votes vote down vote up
@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();
    }
}
 
Example #6
Source File: ApiResource.java    From OpenAs2App with BSD 2-Clause "Simplified" License 5 votes vote down vote up
@RolesAllowed("ADMIN")
@HEAD
@Path("/{resource}{action:(/[^/]+?)?}{id:(/[^/]+?)?}")
public Response headCommand(@PathParam("param") String command) {
    // Just an Empty response
    return Response.status(200).build();
}
 
Example #7
Source File: Util.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #8
Source File: HttpResourceModel.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #9
Source File: StockQuoteService.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #10
Source File: StockQuoteService.java    From msf4j with Apache License 2.0 5 votes vote down vote up
/**
 * 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();
}
 
Example #11
Source File: HttpMethodAnnotationHandlerTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleHEADAnnotation() throws Exception {
	HEADAnnotationHandler handler = new HEADAnnotationHandler();
	handler.handle(metaData, mock(HEAD.class), DummyResource.class.getMethod("head"));
	assertTrue(! metaData.getResourceMethods().isEmpty());
	assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy", HttpMethod.HEAD, DummyResource.class.getMethod("head")));
}
 
Example #12
Source File: HttpClientSourceIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@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();
  }

}
 
Example #13
Source File: PingResource.java    From cassandra-reaper with Apache License 2.0 5 votes vote down vote up
@HEAD
public Response headPing() {
  LOG.debug("ping called");

  return healthCheck.execute().isHealthy()
      ? Response.noContent().build()
      : Response.serverError().build();
}
 
Example #14
Source File: OrderResource.java    From resteasy-examples with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example #15
Source File: EcrfStatusEntryResource.java    From ctsms with GNU Lesser General Public License v2.1 5 votes vote down vote up
@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;
}
 
Example #16
Source File: FakeRoot.java    From archistar-core with GNU General Public License v2.0 5 votes vote down vote up
@HEAD
@Path("{id:.+}")
@Produces("text/plain")
public Response getStatById(@PathParam("id") String id,
        @HeaderParam("X-Bucket") String bucket
) throws ReconstructionException, NoSuchAlgorithmException {

    if (!this.buckets.containsKey(bucket)) {
        return Response.accepted().status(404).entity(bucketNotFound(bucket)).build();
    } else {
        return this.buckets.get(bucket).getStatById(id);
    }
}
 
Example #17
Source File: AdminResource.java    From component-runtime with Apache License 2.0 5 votes vote down vote up
@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());
}
 
Example #18
Source File: MicroserviceMetadata.java    From msf4j with Apache License 2.0 5 votes vote down vote up
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);
}
 
Example #19
Source File: ODataSubLocator.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@POST
public Response handlePost(@HeaderParam("X-HTTP-Method") final String xHttpMethod) throws ODataException {
  Response response;

  if (xHttpMethod == null) {
    response = handle(ODataHttpMethod.POST);
  } else {
    /* tunneling */
    if ("MERGE".equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.MERGE);
    } else if ("PATCH".equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.PATCH);
    } else if (HttpMethod.DELETE.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.DELETE);
    } else if (HttpMethod.PUT.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.PUT);
    } else if (HttpMethod.GET.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.GET);
    } else if (HttpMethod.POST.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.POST);
    } else if (HttpMethod.HEAD.equals(xHttpMethod)) {
      response = handleHead();
    } else if (HttpMethod.OPTIONS.equals(xHttpMethod)) {
      response = handleOptions();
    } else {
      response = returnNotImplementedResponse(ODataNotImplementedException.TUNNELING);
    }
  }
  return response;
}
 
Example #20
Source File: HttpMethodAnnotationHandlerTest.java    From minnal with Apache License 2.0 5 votes vote down vote up
@Test
public void shouldHandleHEADAnnotationWithPath() throws Exception {
	HEADAnnotationHandler handler = new HEADAnnotationHandler();
	handler.handle(metaData, mock(HEAD.class), DummyResource.class.getMethod("headWithPath"));
	assertTrue(! metaData.getResourceMethods().isEmpty());
	assertEquals(metaData.getResourceMethods().iterator().next(), new ResourceMethodMetaData("/dummy/head", HttpMethod.HEAD, DummyResource.class.getMethod("headWithPath")));
}
 
Example #21
Source File: HttpClientSourceIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Test
public void testBatchHead() 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.POLLING;
  conf.headers.put("abcdef", "ghijkl");
  conf.resourceUrl = getBaseUri() + "headers";
  conf.client.readTimeoutMillis = 1000;
  conf.basic.maxBatchSize = 100;
  conf.basic.maxWaitTime = 1000;
  conf.pollingInterval = 5000;
  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();
  }

}
 
Example #22
Source File: HttpProcessorIT.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@HEAD
public Response head() {
  return Response.ok()
          .header("x-test-header", "StreamSets")
          .header("x-list-header", ImmutableList.of("a", "b"))
          .build();
}
 
Example #23
Source File: QueueResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@HEAD
@Produces("application/xml")
public Response head(@Context UriInfo uriInfo) {
   ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getRequestUri() + "\"");

   Response.ResponseBuilder builder = Response.ok();
   setSenderLink(builder, uriInfo);
   setSenderWithIdLink(builder, uriInfo);
   setConsumersLink(builder, uriInfo);
   setPushConsumersLink(builder, uriInfo);
   return builder.build();
}
 
Example #24
Source File: SubscriptionsResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Path("auto-ack/{consumer-id}")
@HEAD
public Response headAutoAckSubscription(@PathParam("consumer-id") String consumerId,
                                        @Context UriInfo uriInfo) throws Exception {
   ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\"");

   return internalHeadAutoAckSubscription(uriInfo, consumerId);
}
 
Example #25
Source File: SubscriptionsResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@Path("acknowledged/{consumer-id}")
@HEAD
public Response headAcknowledgedConsumer(@PathParam("consumer-id") String consumerId,
                                         @Context UriInfo uriInfo) throws Exception {
   ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\"");

   return internalHeadAcknowledgedConsumer(uriInfo, consumerId);
}
 
Example #26
Source File: TopicResource.java    From activemq-artemis with Apache License 2.0 5 votes vote down vote up
@HEAD
@Produces("application/xml")
public Response head(@Context UriInfo uriInfo) {
   ActiveMQRestLogger.LOGGER.debug("Handling HEAD request for \"" + uriInfo.getPath() + "\"");

   Response.ResponseBuilder builder = Response.ok();
   setSenderLink(builder, uriInfo);
   setSenderWithIdLink(builder, uriInfo);
   setSubscriptionsLink(builder, uriInfo);
   setPushSubscriptionsLink(builder, uriInfo);
   return builder.build();
}
 
Example #27
Source File: ODataSubLocator.java    From olingo-odata2 with Apache License 2.0 5 votes vote down vote up
@POST
public Response handlePost(@HeaderParam("X-HTTP-Method") final String xHttpMethod) throws ODataException {
  Response response;

  if (xHttpMethod == null) {
    response = handle(ODataHttpMethod.POST);
  } else {
    /* tunneling */
    if ("MERGE".equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.MERGE);
    } else if ("PATCH".equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.PATCH);
    } else if (HttpMethod.DELETE.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.DELETE);
    } else if (HttpMethod.PUT.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.PUT);
    } else if (HttpMethod.GET.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.GET);
    } else if (HttpMethod.POST.equals(xHttpMethod)) {
      response = handle(ODataHttpMethod.POST);
    } else if (HttpMethod.HEAD.equals(xHttpMethod)) {
      response = handleHead();
    } else if (HttpMethod.OPTIONS.equals(xHttpMethod)) {
      response = handleOptions();
    } else {
      response = returnNotImplementedResponse(ODataNotImplementedException.TUNNELING);
    }
  }
  return response;
}
 
Example #28
Source File: ApiPermissionInfoGenerator.java    From cloudbreak with Apache License 2.0 5 votes vote down vote up
private static String getMethodType(Method method) {
    Set<String> httpAnnotations = Lists.newArrayList(GET.class, DELETE.class, PUT.class, POST.class, HEAD.class, OPTIONS.class, PATCH.class)
            .stream()
            .filter(httpAnnotation -> method.isAnnotationPresent(httpAnnotation))
            .map(httpAnnotation -> httpAnnotation.getSimpleName())
            .collect(Collectors.toSet());
    return Joiner.on(" ").join(httpAnnotations);
}
 
Example #29
Source File: ODataSubLocator.java    From cloud-odata-java with Apache License 2.0 5 votes vote down vote up
@HEAD
public Response handleHead() throws ODataException {
  // RFC 2616, 5.1.1: "An origin server SHOULD return the status code [...]
  // 501 (Not Implemented) if the method is unrecognized or not implemented
  // by the origin server."
  return returnNotImplementedResponse(ODataNotImplementedException.COMMON);
}
 
Example #30
Source File: CorsResource.java    From seed with Mozilla Public License 2.0 5 votes vote down vote up
@HEAD
public Response head(@Context HttpServletRequest httpServletRequest) {
    if ((Boolean) httpServletRequest.getAttribute("cors.isCorsRequest"))
        return Response.ok().build();
    else
        return Response.serverError().build();
}