javax.ws.rs.GET Java Examples

The following examples show how to use javax.ws.rs.GET. 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: VideosResource.java    From hmdm-server with Apache License 2.0 7 votes vote down vote up
@GET
@Path("/{fileName}")
@Produces({"application/octet-stream"})
public javax.ws.rs.core.Response downloadVideo(@PathParam("fileName") String fileName) throws Exception {
    File videoDir = new File(this.videoDirectory);
    if (!videoDir.exists()) {
        videoDir.mkdirs();
    }

    File videoFile = new File(videoDir, URLDecoder.decode(fileName, "UTF8"));
    if (!videoFile.exists()) {
        return javax.ws.rs.core.Response.status(404).build();
    } else {
        ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(videoFile.getName()).creationDate(new Date()).build();
        return javax.ws.rs.core.Response.ok( ( StreamingOutput ) output -> {
            try {
                InputStream input = new FileInputStream( videoFile );
                IOUtils.copy(input, output);
                output.flush();
            } catch ( Exception e ) { e.printStackTrace(); }
        } ).header( "Content-Disposition", contentDisposition ).build();

    }
}
 
Example #2
Source File: ExperimentRestApi.java    From submarine with Apache License 2.0 6 votes vote down vote up
@GET
@Path("/logs/{id}")
@Operation(summary = "Log experiment by id",
        tags = {"experiment"},
        responses = {
                @ApiResponse(description = "successful operation", content = @Content(
                        schema = @Schema(implementation = JsonResponse.class))),
                @ApiResponse(responseCode = "404", description = "Experiment not found")})
public Response getLog(@PathParam(RestConstants.ID) String id) {
  try {
    ExperimentLog experimentLog = experimentManager.getExperimentLog(id);
    return new JsonResponse.Builder<ExperimentLog>(Response.Status.OK).success(true)
        .result(experimentLog).build();

  } catch (SubmarineRuntimeException e) {
    return parseExperimentServiceException(e);
  }
}
 
Example #3
Source File: StramWebServices.java    From Bats with Apache License 2.0 6 votes vote down vote up
@GET
@Path(PATH_LOGICAL_PLAN_OPERATORS + "/{operatorName}/ports")
@Produces(MediaType.APPLICATION_JSON)
public JSONObject getPorts(@PathParam("operatorName") String operatorName)
{
  init();
  OperatorMeta logicalOperator = dagManager.getLogicalPlan().getOperatorMeta(operatorName);
  Set<LogicalPlan.InputPortMeta> inputPorts;
  Set<LogicalPlan.OutputPortMeta> outputPorts;
  if (logicalOperator == null) {
    ModuleMeta logicalModule = dagManager.getModuleMeta(operatorName);
    if (logicalModule == null) {
      throw new NotFoundException();
    }
    inputPorts = logicalModule.getInputStreams().keySet();
    outputPorts = logicalModule.getOutputStreams().keySet();
  } else {
    inputPorts = logicalOperator.getInputStreams().keySet();
    outputPorts = logicalOperator.getOutputStreams().keySet();
  }

  JSONObject result = getPortsObjects(inputPorts, outputPorts);
  return result;
}
 
Example #4
Source File: Application.java    From camel-k-runtime with Apache License 2.0 6 votes vote down vote up
@SuppressWarnings("unchecked")
@GET
@Path("/inspect")
@Consumes(MediaType.TEXT_PLAIN)
@Produces(MediaType.APPLICATION_JSON)
public JsonObject inspect() {
    var endpoint = context.getEndpoint("knative:endpoint/from", KnativeEndpoint.class);
    var envMeta = endpoint.getConfiguration().getEnvironment().lookup(Knative.Type.endpoint, "from")
        .filter(entry -> Knative.EndpointKind.source.name().equals(entry.getMetadata().get(Knative.CAMEL_ENDPOINT_KIND)))
        .findFirst()
        .map(def -> Json.createObjectBuilder((Map)def.getMetadata()))
        .orElseThrow(IllegalArgumentException::new);

    return Json.createObjectBuilder()
        .add("env-meta", envMeta)
        .build();
}
 
Example #5
Source File: SetsResource.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@GET
@Path("/{namespace}/{set}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Get entries from a set")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200",
                 description = "Provides entry names and weights matching query parameters as properties in a json",
                 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 get(@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 for values in set/namespace {}/{}", set, namespace);
    logger.debug("request parameters: {}", bean);
    final Map<String, Long> entries = this.cantor.sets().get(
            namespace,
            set,
            bean.getMin(),
            bean.getMax(),
            bean.getStart(),
            bean.getCount(),
            bean.isAscending());
    return Response.ok(parser.toJson(entries)).build();
}
 
Example #6
Source File: SetsResource.java    From cantor with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@GET
@Path("/intersect/{namespace}")
@Produces(MediaType.APPLICATION_JSON)
@Operation(summary = "Perform an intersection of all provided sets")
@ApiResponses(value = {
    @ApiResponse(responseCode = "200",
                 description = "Provides an intersection of all entries filtered by query parameters as properties in a json",
                 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 intersect(@Parameter(description = "Namespace identifier") @PathParam("namespace") final String namespace,
                          @Parameter(description = "List of sets") @QueryParam("set") final List<String> sets,
                          @BeanParam final SetsDataSourceBean bean) throws IOException {
    logger.info("received request for intersection of sets {} in namespace {}", sets, namespace);
    logger.debug("request parameters: {}", bean);
    final Map<String, Long> intersection = this.cantor.sets().intersect(
            namespace,
            sets,
            bean.getMin(),
            bean.getMax(),
            bean.getStart(),
            bean.getCount(),
            bean.isAscending());
    return Response.ok(parser.toJson(intersection)).build();
}
 
Example #7
Source File: UserResource.java    From hmdm-server with Apache License 2.0 6 votes vote down vote up
@ApiOperation(
        value = "Get current user details",
        notes = "Returns the details for the current user account",
        response = User.class
)
@GET
@Path("/current")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public Response getCurrentUserDetails() {
    return SecurityContext.get().getCurrentUser().map(u -> {
        User userDetails = userDAO.getUserDetails(u.getId());
        userDetails.setPassword(null);

        return Response.OK(userDetails);
    }).orElse(Response.OK(null));
}
 
Example #8
Source File: MetricsResource.java    From metrics with Apache License 2.0 6 votes vote down vote up
@GET
@Produces({Constants.PRODUCE_JSON_WITH_QUALITY_SOURCE, MediaType.TEXT_HTML})
@Path("/specific")
public Response getMetric(final @QueryParam("metric") Set<String> metricNames, @QueryParam("zeroIgnore") boolean zeroIgnore) {

    if (!manager.isEnabled()) {
        return Response.status(Response.Status.FORBIDDEN).build();
    }

    MetricName name = baseName.tagged("url", "/specific").level(MetricLevel.TRIVIAL);
    Timer urlTimer = manager.getTimer("metrics", name, ReservoirType.BUCKET);
    Timer.Context context = urlTimer.time();
    try {
        return getMetricsInternal(metricNames, zeroIgnore);
    } finally {
        context.stop();
    }
}
 
Example #9
Source File: QueryResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@ResourceSecurity(AUTHENTICATED_USER)
@GET
public List<BasicQueryInfo> getAllQueryInfo(@QueryParam("state") String stateFilter, @Context HttpServletRequest servletRequest, @Context HttpHeaders httpHeaders)
{
    QueryState expectedState = stateFilter == null ? null : QueryState.valueOf(stateFilter.toUpperCase(Locale.ENGLISH));

    List<BasicQueryInfo> queries = dispatchManager.getQueries();
    queries = filterQueries(extractAuthorizedIdentity(servletRequest, httpHeaders, accessControl, groupProvider), queries, accessControl);

    ImmutableList.Builder<BasicQueryInfo> builder = new ImmutableList.Builder<>();
    for (BasicQueryInfo queryInfo : queries) {
        if (stateFilter == null || queryInfo.getState() == expectedState) {
            builder.add(queryInfo);
        }
    }
    return builder.build();
}
 
Example #10
Source File: TestingHttpBackupResource.java    From presto with Apache License 2.0 6 votes vote down vote up
@GET
@Path("{uuid}")
@Produces(APPLICATION_OCTET_STREAM)
public synchronized Response getRequest(
        @HeaderParam(PRESTO_ENVIRONMENT) String environment,
        @PathParam("uuid") UUID uuid)
{
    checkEnvironment(environment);
    if (!shards.containsKey(uuid)) {
        return Response.status(NOT_FOUND).build();
    }
    byte[] bytes = shards.get(uuid);
    if (bytes == null) {
        return Response.status(GONE).build();
    }
    return Response.ok(bytes).build();
}
 
Example #11
Source File: AvroResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/genericMarshalUnmarshalUsingConfigureTimeAvroDataFormat/{value}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String genericMarshalUsingConfigureTimeAvroDataFormat(@PathParam("value") String value) {
    GenericRecord input = new GenericData.Record(getSchema());
    input.put("name", value);
    Object marshalled = producerTemplate.requestBody("direct:marshalUsingConfigureTimeAvroDataFormat", input);
    GenericRecord output = producerTemplate.requestBody("direct:unmarshalUsingConfigureTimeAvroDataFormat", marshalled,
            GenericRecord.class);
    return output.get("name").toString();
}
 
Example #12
Source File: SecuredService.java    From microshed-testing with Apache License 2.0 5 votes vote down vote up
@GET
@PermitAll
@Path("/headers")
public String getHeaders() {
	String result =  "*** HEADERS: " + headers.getRequestHeaders().toString();
	result += "\n" + "*** SUBJECT: " + ( callerPrincipal == null ? "null" : callerPrincipal.getSubject());
	result += "\n" + "**** ISSUER: " + System.getenv("mp_jwt_verify_issuer");
	return result;
}
 
Example #13
Source File: Api.java    From apicurio-registry with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/schemas/{schemaid}/versions/{versionnum}")
@Produces({"application/json", "application/vnd.apache.avro+json"})
public Schema apiSchemasSchemaidVersionsVersionnumGet(@PathParam("schemaid") String schemaid, @PathParam("versionnum") int versionnum)
throws ArtifactNotFoundException {
    return service.apiSchemasSchemaidVersionsVersionnumGet(schemaid, versionnum);
}
 
Example #14
Source File: MustacheResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/templateWithPartials")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String templateWithPartials() {
    LOG.infof("Calling templateWithPartials");
    return template.requestBody("mustache://template/includer.mustache", null, String.class);
}
 
Example #15
Source File: TaskResource.java    From presto with Apache License 2.0 5 votes vote down vote up
@ResourceSecurity(INTERNAL_ONLY)
@GET
@Path("{taskId}/status")
@Produces(MediaType.APPLICATION_JSON)
public void getTaskStatus(
        @PathParam("taskId") TaskId taskId,
        @HeaderParam(PRESTO_CURRENT_STATE) TaskState currentState,
        @HeaderParam(PRESTO_MAX_WAIT) Duration maxWait,
        @Context UriInfo uriInfo,
        @Suspended AsyncResponse asyncResponse)
{
    requireNonNull(taskId, "taskId is null");

    if (currentState == null || maxWait == null) {
        TaskStatus taskStatus = taskManager.getTaskStatus(taskId);
        asyncResponse.resume(taskStatus);
        return;
    }

    Duration waitTime = randomizeWaitTime(maxWait);
    // TODO: With current implementation, a newly completed driver group won't trigger immediate HTTP response,
    // leading to a slight delay of approx 1 second, which is not a major issue for any query that are heavy weight enough
    // to justify group-by-group execution. In order to fix this, REST endpoint /v1/{task}/status will need change.
    ListenableFuture<TaskStatus> futureTaskStatus = addTimeout(
            taskManager.getTaskStatus(taskId, currentState),
            () -> taskManager.getTaskStatus(taskId),
            waitTime,
            timeoutExecutor);

    // For hard timeout, add an additional time to max wait for thread scheduling contention and GC
    Duration timeout = new Duration(waitTime.toMillis() + ADDITIONAL_WAIT_TIME.toMillis(), MILLISECONDS);
    bindAsyncResponse(asyncResponse, futureTaskStatus, responseExecutor)
            .withTimeout(timeout);
}
 
Example #16
Source File: EntriesProxyResource.java    From browserup-proxy with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/assertStatusInformational")
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "In case url pattern is provided assert that all responses " +
        "found by url pattern have statuses belonging to INFORMATIONAL class (1xx), otherwise " +
        "assert that all responses of current step have statuses belonging to INFORMATIONAL class (1xx)",
        responses = {@ApiResponse(
                description = "Assertion result",
                content = @Content(
                        mediaType = MediaType.APPLICATION_JSON,
                        schema = @Schema(implementation = AssertionResult.class)))})
public AssertionResult statusInformational(
        @PathParam(PORT)
        @NotNullConstraint(paramName = PORT)
        @PortWithExistingProxyConstraint
        @Parameter(required = true, in = ParameterIn.PATH, description = DocConstants.PORT_DESCRIPTION) int port,

        @QueryParam(URL_PATTERN)
        @PatternConstraint(paramName = URL_PATTERN)
        @Parameter(description = DocConstants.URL_PATTERN_DESCRIPTION) String urlPattern) {

    MitmProxyServer proxyServer = proxyManager.get(port);

    return StringUtils.isEmpty(urlPattern) ?
            proxyServer.assertResponseStatusCode(HttpStatusClass.INFORMATIONAL) :
            proxyServer.assertResponseStatusCode(Pattern.compile(urlPattern), HttpStatusClass.INFORMATIONAL);
}
 
Example #17
Source File: ZoneInfoEndpoint.java    From Hands-On-Enterprise-Java-Microservices-with-Eclipse-MicroProfile with MIT License 5 votes vote down vote up
@GET
@Path("/userTZ")
@RolesAllowed("WorldClockSubscriber")
@Produces(MediaType.TEXT_PLAIN)
@Timed
public String getSubscriberZoneInfo() {
    System.out.printf("Zoneinfo for %s: %s\n", jwt.getName(), zoneinfo);
    return zoneinfo;
}
 
Example #18
Source File: OAuthResource.java    From clouditor with Apache License 2.0 5 votes vote down vote up
@GET
@Path("profile")
public Profile getProfile() {
  var profile = new Profile();
  profile.setEnabled(
      this.engine.getOAuthClientId() != null
          && this.engine.getOAuthClientSecret() != null
          && this.engine.getOAuthAuthUrl() != null
          && this.engine.getOAuthTokenUrl() != null
          && this.engine.getOAuthJwtSecret() != null);

  return profile;
}
 
Example #19
Source File: RenewSwitchResource.java    From sofa-registry with Apache License 2.0 5 votes vote down vote up
/**
 * enable both
 */
@GET
@Path("enable")
@Produces(MediaType.APPLICATION_JSON)
public Result enableRenew() {
    invokeSession("true");
    invokeData("true");

    Result result = new Result();
    result.setSuccess(true);
    return result;
}
 
Example #20
Source File: StorageResources.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/storage/{name}/enable/{val}")
@Produces(MediaType.APPLICATION_JSON)
public JsonResult enablePlugin(@PathParam("name") String name, @PathParam("val") Boolean enable) {
  PluginConfigWrapper plugin = getPluginConfig(name);
  try {
    return plugin.setEnabledInStorage(storage, enable)
        ? message("Success")
        : message("Error (plugin does not exist)");
  } catch (ExecutionSetupException e) {
    logger.debug("Error in enabling storage name: {} flag: {}",  name, enable);
    return message("Error (unable to enable / disable storage)");
  }
}
 
Example #21
Source File: ParamRestApi.java    From submarine with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/{id}")
@SubmarineApi
public Response getParam(@PathParam("id") String id) {
  LOG.info("getParam ({})", id);
  
  Param param;
  try {
    param = paramService.selectById(id);
  } catch (Exception e) {
    LOG.error(e.toString());
    return new JsonResponse.Builder<Boolean>(Response.Status.OK).success(false).build();
  }
  return new JsonResponse.Builder<Param>(Response.Status.OK).success(true).result(param).build();
}
 
Example #22
Source File: AsyncResource.java    From quarkus-deep-dive with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/async/{name}")
public CompletionStage<String> message(@PathParam("name") String name) {
    return bus.<String>send("some-address", name)
            .thenApply(Message::body)
            .thenApply(String::toUpperCase);
}
 
Example #23
Source File: DrillRoot.java    From Bats with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/portNum")
@Produces(MediaType.APPLICATION_JSON)
public Map<String, Integer> getPortNum() {

  final DrillConfig config = work.getContext().getConfig();
  final int port = config.getInt(ExecConstants.HTTP_PORT);
  Map<String, Integer> portMap = new HashMap<String, Integer>();
  portMap.put("port", port);
  return portMap;
}
 
Example #24
Source File: Order.java    From micro-integrator with Apache License 2.0 5 votes vote down vote up
@GET
@Path("products/{productId}/")
public Product getProduct(@PathParam("productId") int productId) {
    System.out.println("----invoking getProduct with id: " + productId);
    Product p = products.get(new Long(productId));
    return p;
}
 
Example #25
Source File: MockMailbox.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/size")
@Produces(MediaType.TEXT_PLAIN)
public String getSize(@PathParam("username") String username) throws Exception {
    Mailbox mailbox = Mailbox.get(username);
    return Integer.toString(mailbox.size());
}
 
Example #26
Source File: Application.java    From camel-k-runtime with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/services")
@Produces(MediaType.APPLICATION_JSON)
public JsonObject getServices() {
    JsonArrayBuilder builder = Json.createArrayBuilder();

    ServiceLoader.load(Runtime.Listener.class).forEach(listener -> {
        builder.add(listener.getClass().getName());
    });

    return Json.createObjectBuilder()
        .add("services", builder)
        .build();
}
 
Example #27
Source File: BookStoreEndpoint.java    From ebook-Building-an-API-Backend-with-MicroProfile with Apache License 2.0 5 votes vote down vote up
@Counted(unit = MetricUnits.NONE,
        name = "getBook",
        absolute = true,
        monotonic = true,
        displayName = "get single book",
        description = "Monitor how many times getBook method was called")
@GET
@Path("{id}")
public Response getBook(@PathParam("id") Long id) {
    Book book = bookService.findById(id);

    return Response.ok(book).build();
}
 
Example #28
Source File: AvroResource.java    From camel-quarkus with Apache License 2.0 5 votes vote down vote up
@Path("/valueMarshalUnmarshalUsingSchemaAvroDsl/{value}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String valueMarshalUnmarshalUsingSchemaAvroDsl(@PathParam("value") String value) {
    Value input = Value.newBuilder().setValue(value).build();
    Object marshalled = producerTemplate.requestBody("direct:marshalUsingAvroDsl", input);
    Value output = producerTemplate.requestBody("direct:unmarshalUsingSchemaAvroDsl", marshalled, Value.class);
    return output.getValue().toString();
}
 
Example #29
Source File: MetaStoreRestApi.java    From submarine with Apache License 2.0 5 votes vote down vote up
@GET
@Path("/table/count")
@SubmarineApi
public Response getTableCount() {
  int tableCount;
  try {
    tableCount = submarineMetaStore.getTableCount();
  } catch (MetaException e) {
    LOG.error(e.getMessage(), e);
    return new JsonResponse.Builder<String>(Response.Status.INTERNAL_SERVER_ERROR)
            .success(false).build();
  }
  return new JsonResponse.Builder<Integer>(Response.Status.OK)
          .success(true).result(tableCount).build();
}
 
Example #30
Source File: ReactiveRestResourceTemplate.java    From kogito-runtimes with Apache License 2.0 5 votes vote down vote up
@GET()
@Path("/{id}")
@Produces(MediaType.APPLICATION_JSON)
public CompletionStage<$Type$Output> getResource_$name$(@PathParam("id") String id) {
    return CompletableFuture.supplyAsync(() -> {
        return process.instances()
                .findById(id)
                .map(pi -> mapOutput(new $Type$Output(), pi.variables()))
                .orElse(null);
    });
}