org.glassfish.jersey.server.ManagedAsync Java Examples

The following examples show how to use org.glassfish.jersey.server.ManagedAsync. 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: PinotClientRequest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@POST
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Path("query/sql")
@ApiOperation(value = "Querying pinot using sql")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Query response"), @ApiResponse(code = 500, message = "Internal Server Error")})
public void processSqlQueryPost(String query, @Suspended AsyncResponse asyncResponse) {
  try {
    JsonNode requestJson = JsonUtils.stringToJsonNode(query);
    if (!requestJson.has(Request.SQL)) {
      throw new IllegalStateException("Payload is missing the query string field 'sql'");
    }
    String queryOptions = constructSqlQueryOptions();
    // the only query options as of now are sql related. do not allow any custom query options in sql endpoint
    ObjectNode sqlRequestJson = ((ObjectNode) requestJson).put(Request.QUERY_OPTIONS, queryOptions);
    BrokerResponse brokerResponse = requestHandler.handleRequest(sqlRequestJson, null, new RequestStatistics());
    asyncResponse.resume(brokerResponse.toJsonString());
  } catch (Exception e) {
    LOGGER.error("Caught exception while processing POST request", e);
    brokerMetrics.addMeteredGlobalValue(BrokerMeter.UNCAUGHT_POST_EXCEPTIONS, 1L);
    asyncResponse.resume(new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR));
  }
}
 
Example #2
Source File: OrderService.java    From qcon-microservices with Apache License 2.0 6 votes vote down vote up
/**
 * Perform a "Long-Poll" styled get. This method will attempt to get the value for the passed key
 * blocking until the key is available or passed timeout is reached. Non-blocking IO is used to
 * implement this, but the API will block the calling thread if no data is available
 *
 * @param id - the key of the value to retrieve
 * @param timeout - the timeout for the long-poll
 * @param asyncResponse - async response used to trigger the poll early should the appropriate
 * value become available
 */
@GET
@ManagedAsync
@Path("/orders/{id}")
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public void getWithTimeout(@PathParam("id") final String id,
                           @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) Long timeout,
                           @Suspended final AsyncResponse asyncResponse) {
    setTimeout(timeout, asyncResponse);

    log.info("running GET on this node");
    try {
        Order order = ordersStore().get(id);
        if (order == null) {
            log.info("Delaying get as order not present for id " + id);
            outstandingRequests.put(id, new FilteredResponse<>(asyncResponse, (k, v) -> true));
        } else {
            asyncResponse.resume(order);
        }
    } catch (InvalidStateStoreException e) {
        //Store not ready so delay
        log.info("Delaying request for " + id + " because state store is not ready.");
        outstandingRequests.put(id, new FilteredResponse<>(asyncResponse, (k, v) -> true));
    }
}
 
Example #3
Source File: PinotClientRequest.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@POST
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Path("query")
@ApiOperation(value = "Querying pinot")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Query response"), @ApiResponse(code = 500, message = "Internal Server Error")})
public void processQueryPost(String query, @Suspended AsyncResponse asyncResponse) {
  try {
    JsonNode requestJson = JsonUtils.stringToJsonNode(query);
    BrokerResponse brokerResponse = requestHandler.handleRequest(requestJson, null, new RequestStatistics());
    asyncResponse.resume(brokerResponse);
  } catch (Exception e) {
    LOGGER.error("Caught exception while processing POST request", e);
    brokerMetrics.addMeteredGlobalValue(BrokerMeter.UNCAUGHT_POST_EXCEPTIONS, 1L);
    throw new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR);
  }
}
 
Example #4
Source File: TasksResource.java    From dcos-cassandra-service with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/{name}/status")
@ManagedAsync
public void getStatus(
    @PathParam("name") final String name,
    @Suspended final AsyncResponse response) {

    Optional<CassandraDaemonTask> taskOption =
        Optional.ofNullable(state.getDaemons().get(name));
    if (!taskOption.isPresent()) {
        response.resume(
            Response.status(Response.Status.NOT_FOUND).build());
    } else {
        CassandraDaemonTask task = taskOption.get();
        client.status(task.getHostname(), task.getExecutor().getApiPort()
        ).whenCompleteAsync((status, error) -> {
            if (status != null) {
                response.resume(status);
            } else {
                response.resume(Response.serverError());
            }
        });
    }
}
 
Example #5
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@POST
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/segments")
@ApiOperation(value = "Upload a segment", notes = "Upload a segment as json")
// We use this endpoint with URI upload because a request sent with the multipart content type will reject the POST
// request if a multipart object is not sent. This endpoint does not move the segment to its final location;
// it keeps it at the downloadURI header that is set. We will not support this endpoint going forward.
public void uploadSegmentAsJson(String segmentJsonStr,
    @ApiParam(value = "Name of the table") @QueryParam(FileUploadDownloadClient.QueryParameters.TABLE_NAME) String tableName,
    @ApiParam(value = "Whether to enable parallel push protection") @DefaultValue("false") @QueryParam(FileUploadDownloadClient.QueryParameters.ENABLE_PARALLEL_PUSH_PROTECTION) boolean enableParallelPushProtection,
    @Context HttpHeaders headers, @Context Request request, @Suspended final AsyncResponse asyncResponse) {
  try {
    asyncResponse.resume(uploadSegment(tableName, null, enableParallelPushProtection, headers, request, false));
  } catch (Throwable t) {
    asyncResponse.resume(t);
  }
}
 
Example #6
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@POST
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/segments")
@ApiOperation(value = "Upload a segment", notes = "Upload a segment as binary")
// For the multipart endpoint, we will always move segment to final location regardless of the segment endpoint.
public void uploadSegmentAsMultiPart(FormDataMultiPart multiPart,
    @ApiParam(value = "Name of the table") @QueryParam(FileUploadDownloadClient.QueryParameters.TABLE_NAME) String tableName,
    @ApiParam(value = "Whether to enable parallel push protection") @DefaultValue("false") @QueryParam(FileUploadDownloadClient.QueryParameters.ENABLE_PARALLEL_PUSH_PROTECTION) boolean enableParallelPushProtection,
    @Context HttpHeaders headers, @Context Request request, @Suspended final AsyncResponse asyncResponse) {
  try {
    asyncResponse.resume(uploadSegment(tableName, multiPart, enableParallelPushProtection, headers, request, true));
  } catch (Throwable t) {
    asyncResponse.resume(t);
  }
}
 
Example #7
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@POST
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
@Path("/v2/segments")
@ApiOperation(value = "Upload a segment", notes = "Upload a segment as json")
// We use this endpoint with URI upload because a request sent with the multipart content type will reject the POST
// request if a multipart object is not sent. This endpoint is recommended for use. It differs from the first
// endpoint in how it moves the segment to a Pinot-determined final directory.
public void uploadSegmentAsJsonV2(String segmentJsonStr,
    @ApiParam(value = "Name of the table") @QueryParam(FileUploadDownloadClient.QueryParameters.TABLE_NAME) String tableName,
    @ApiParam(value = "Whether to enable parallel push protection") @DefaultValue("false") @QueryParam(FileUploadDownloadClient.QueryParameters.ENABLE_PARALLEL_PUSH_PROTECTION) boolean enableParallelPushProtection,
    @Context HttpHeaders headers, @Context Request request, @Suspended final AsyncResponse asyncResponse) {
  try {
    asyncResponse.resume(uploadSegment(tableName, null, enableParallelPushProtection, headers, request, true));
  } catch (Throwable t) {
    asyncResponse.resume(t);
  }
}
 
Example #8
Source File: PinotSegmentUploadDownloadRestletResource.java    From incubator-pinot with Apache License 2.0 6 votes vote down vote up
@POST
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Path("/v2/segments")
@ApiOperation(value = "Upload a segment", notes = "Upload a segment as binary")
// This behavior does not differ from v1 of the same endpoint.
public void uploadSegmentAsMultiPartV2(FormDataMultiPart multiPart,
    @ApiParam(value = "Name of the table") @QueryParam(FileUploadDownloadClient.QueryParameters.TABLE_NAME) String tableName,
    @ApiParam(value = "Whether to enable parallel push protection") @DefaultValue("false") @QueryParam(FileUploadDownloadClient.QueryParameters.ENABLE_PARALLEL_PUSH_PROTECTION) boolean enableParallelPushProtection,
    @Context HttpHeaders headers, @Context Request request, @Suspended final AsyncResponse asyncResponse) {
  try {
    asyncResponse.resume(uploadSegment(tableName, multiPart, enableParallelPushProtection, headers, request, true));
  } catch (Throwable t) {
    asyncResponse.resume(t);
  }
}
 
Example #9
Source File: TestResource.java    From brave with Apache License 2.0 5 votes vote down vote up
@GET
@Path("managedAsync")
@ManagedAsync
public void managedAsync(@Suspended AsyncResponse response) {
  if (tracer.currentSpan() == null) {
    response.resume(new IllegalStateException("couldn't read current span!"));
    return;
  }
  response.resume("foo");
}
 
Example #10
Source File: ExampleResource.java    From dynein with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/sqs-delayed")
@Timed
@ManagedAsync
public void scheduleSqsDelayed(
    @QueryParam("name") Optional<String> name,
    @QueryParam("delaySeconds") Optional<Integer> delaySeconds,
    @Suspended final AsyncResponse asyncResponse) {
  scheduleJob(name, delaySeconds, JobScheduleType.SQS_DELAYED, asyncResponse);
}
 
Example #11
Source File: PinotClientRequest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@GET
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Path("query/sql")
@ApiOperation(value = "Querying pinot using sql")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Query response"), @ApiResponse(code = 500, message = "Internal Server Error")})
public void processSqlQueryGet(@ApiParam(value = "Query", required = true) @QueryParam("sql") String query,
    @ApiParam(value = "Trace enabled") @QueryParam(Request.TRACE) String traceEnabled,
    @ApiParam(value = "Debug options") @QueryParam(Request.DEBUG_OPTIONS) String debugOptions,
    @Suspended AsyncResponse asyncResponse) {
  try {
    ObjectNode requestJson = JsonUtils.newObjectNode();
    requestJson.put(Request.SQL, query);
    String queryOptions = constructSqlQueryOptions();
    requestJson.put(Request.QUERY_OPTIONS, queryOptions);
    if (traceEnabled != null) {
      requestJson.put(Request.TRACE, traceEnabled);
    }
    if (debugOptions != null) {
      requestJson.put(Request.DEBUG_OPTIONS, debugOptions);
    }
    BrokerResponse brokerResponse = requestHandler.handleRequest(requestJson, null, new RequestStatistics());
    asyncResponse.resume(brokerResponse.toJsonString());
  } catch (Exception e) {
    LOGGER.error("Caught exception while processing GET request", e);
    brokerMetrics.addMeteredGlobalValue(BrokerMeter.UNCAUGHT_GET_EXCEPTIONS, 1L);
    asyncResponse.resume(new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR));
  }
}
 
Example #12
Source File: PinotClientRequest.java    From incubator-pinot with Apache License 2.0 5 votes vote down vote up
@GET
@ManagedAsync
@Produces(MediaType.APPLICATION_JSON)
@Path("query")
@ApiOperation(value = "Querying pinot")
@ApiResponses(value = {@ApiResponse(code = 200, message = "Query response"), @ApiResponse(code = 500, message = "Internal Server Error")})
public void processQueryGet(
    // Query param "bql" is for backward compatibility
    @ApiParam(value = "Query", required = true) @QueryParam("bql") String query,
    @ApiParam(value = "Trace enabled") @QueryParam(Request.TRACE) String traceEnabled,
    @ApiParam(value = "Debug options") @QueryParam(Request.DEBUG_OPTIONS) String debugOptions,
    @Suspended AsyncResponse asyncResponse) {
  try {
    ObjectNode requestJson = JsonUtils.newObjectNode();
    requestJson.put(Request.PQL, query);
    if (traceEnabled != null) {
      requestJson.put(Request.TRACE, traceEnabled);
    }
    if (debugOptions != null) {
      requestJson.put(Request.DEBUG_OPTIONS, debugOptions);
    }
    BrokerResponse brokerResponse = requestHandler.handleRequest(requestJson, null, new RequestStatistics());
    asyncResponse.resume(brokerResponse.toJsonString());
  } catch (Exception e) {
    LOGGER.error("Caught exception while processing GET request", e);
    brokerMetrics.addMeteredGlobalValue(BrokerMeter.UNCAUGHT_GET_EXCEPTIONS, 1L);
    asyncResponse.resume(new WebApplicationException(e, Response.Status.INTERNAL_SERVER_ERROR));
  }
}
 
Example #13
Source File: OrderService.java    From qcon-microservices with Apache License 2.0 5 votes vote down vote up
/**
 * Persist an Order to Kafka. Returns once the order is successfully written to R nodes where
 * R is the replication factor configured in Kafka.
 *
 * @param order the order to add
 * @param timeout the max time to wait for the response from Kafka before timing out the POST
 */
@POST
@ManagedAsync
@Path("/orders")
@Consumes(MediaType.APPLICATION_JSON)
public void submitOrder(final Order order,
                        @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) final Long timeout,
                        @Suspended final AsyncResponse response) {
    setTimeout(timeout, response);

    Order bean = order;
    producer.send(new ProducerRecord<>(Schemas.Topics.ORDERS.name(), bean.getId(), bean),
            callback(response, bean.getId()));
}
 
Example #14
Source File: OrderService.java    From qcon-microservices with Apache License 2.0 5 votes vote down vote up
/**
 * Perform a "Long-Poll" styled get. This method will attempt to get the order for the ID
 * blocking until the order has been validated or passed timeout is reached. Non-blocking IO is used to
 * implement this, but the API will block the calling thread if no data is available
 *
 * @param id - the key of the value to retrieve
 * @param timeout - the timeout for the long-poll
 * @param asyncResponse - async response used to trigger the poll early should the appropriate
 * value become available
 */
@GET
@ManagedAsync
@Path("orders/{id}/validated")
@Produces({MediaType.APPLICATION_JSON, MediaType.TEXT_PLAIN})
public void getPostValidationWithTimeout(@PathParam("id") final String id,
                                         @QueryParam("timeout") @DefaultValue(CALL_TIMEOUT) Long timeout,
                                         @Suspended final AsyncResponse asyncResponse) {
    setTimeout(timeout, asyncResponse);

    log.info("running GET on this node");
    try {
        Order order = ordersStore().get(id);
        if (order == null || (order.getState() != OrderState.VALIDATED && order.getState() != OrderState.FAILED)) {
            log.info("Delaying get as a validated order not present for id " + id);
            outstandingRequests.put(id, new FilteredResponse<>(asyncResponse,
                    (k, v) -> (v.getState() == OrderState.VALIDATED || v.getState() == OrderState.FAILED)));
        } else {
            asyncResponse.resume(order);
        }
    } catch (InvalidStateStoreException e) {
        //Store not ready so delay
        log.info("Delaying request for " + id + " because state store is not ready.");
        outstandingRequests.put(id, new FilteredResponse<>(asyncResponse,
                (k, v) -> (v.getState() == OrderState.VALIDATED || v.getState() == OrderState.FAILED)));
    }
}
 
Example #15
Source File: ExampleResource.java    From dynein with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/scheduled")
@Timed
@ManagedAsync
public void scheduleScheduled(
    @QueryParam("name") Optional<String> name,
    @QueryParam("delaySeconds") Optional<Integer> delaySeconds,
    @Suspended final AsyncResponse asyncResponse) {
  scheduleJob(name, delaySeconds, JobScheduleType.SCHEDULED, asyncResponse);
}
 
Example #16
Source File: ExampleResource.java    From dynein with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/immediate")
@Timed
@ManagedAsync
public void scheduleImmediate(
    @QueryParam("name") Optional<String> name,
    @QueryParam("delaySeconds") Optional<Integer> delaySeconds,
    @Suspended final AsyncResponse asyncResponse) {
  scheduleJob(name, Optional.of(0), JobScheduleType.IMMEDIATE, asyncResponse);
}
 
Example #17
Source File: ExecutionStrategyResources.java    From servicetalk with Apache License 2.0 4 votes vote down vote up
@ManagedAsync
@GET
@Path("/managed")
public void managed() {
    // NOOP
}