类javax.ws.rs.GET源码实例Demo

下面列出了怎么用javax.ws.rs.GET的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: hmdm-server   文件: VideosResource.java
@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();

    }
}
 
源代码2 项目: hmdm-server   文件: FilesResource.java
@ApiOperation(
        value = "Download a file",
        notes = "Downloads the content of the file",
        responseHeaders = {@ResponseHeader(name = "Content-Disposition")}
)
@GET
@Path("/{filePath}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public javax.ws.rs.core.Response downloadFile(@PathParam("filePath") @ApiParam("A path to a file") String filePath) throws Exception {
    File file = new File(filePath + "/" + URLDecoder.decode(filePath, "UTF8"));
    if (!file.exists()) {
        return javax.ws.rs.core.Response.status(404).build();
    } else {
        ContentDisposition contentDisposition = ContentDisposition.type("attachment").fileName(file.getName()).creationDate(new Date()).build();
        return javax.ws.rs.core.Response.ok( ( StreamingOutput ) output -> {
            try {
                InputStream input = new FileInputStream( file );
                IOUtils.copy(input, output);
                output.flush();
            } catch ( Exception e ) { e.printStackTrace(); }
        } ).header( "Content-Disposition", contentDisposition ).build();

    }
}
 
源代码3 项目: Bats   文件: StramWebServices.java
@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;
}
 
源代码4 项目: camel-k-runtime   文件: Application.java
@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();
}
 
源代码5 项目: metrics   文件: MetricsResource.java
@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();
    }
}
 
源代码6 项目: cantor   文件: SetsResource.java
@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();
}
 
源代码7 项目: submarine   文件: ExperimentRestApi.java
@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);
  }
}
 
源代码8 项目: presto   文件: QueryResource.java
@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();
}
 
源代码9 项目: presto   文件: TestingHttpBackupResource.java
@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();
}
 
源代码10 项目: hmdm-server   文件: UserResource.java
@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));
}
 
源代码11 项目: cantor   文件: SetsResource.java
@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();
}
 
源代码12 项目: clouditor   文件: OAuthResource.java
@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;
}
 
源代码13 项目: osgi-best-practices   文件: TaskResource.java
@Operation(summary = "Get single task by id", description =  "Get single task by id")
@GET
@Path("{id}")
public Response getTask(@PathParam("id") Integer id) {
    Task task = taskService.getById(id);
    return task == null ? Response.status(Status.NOT_FOUND).build() : Response.ok(task).build();
}
 
源代码14 项目: quarkus-deep-dive   文件: AsyncResource.java
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)
public Publisher<String> stream() {
    return ReactiveStreams.of("a", "b", "c")
            .map(String::toUpperCase)
            .buildRs();
}
 
源代码15 项目: clouditor   文件: AccountsResource.java
@GET
@Path("{provider}")
public CloudAccount getAccount(@PathParam("provider") String provider) {
  provider = sanitize(provider);

  var account = this.service.getAccount(provider);

  if (account == null) {
    throw new NotFoundException();
  }

  return account;
}
 
源代码16 项目: Bats   文件: ProfileResources.java
@GET
@Path("/profiles/{queryid}.json")
@Produces(MediaType.APPLICATION_JSON)
public String getProfileJSON(@PathParam("queryid") String queryId) {
  try {
    return new String(work.getContext().getProfileStoreContext().getProfileStoreConfig().getSerializer().serialize(getQueryProfile(queryId)));
  } catch (Exception e) {
    logger.debug("Failed to serialize profile for: " + queryId);
    return ("{ 'message' : 'error (unable to serialize profile)' }");
  }
}
 
源代码17 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@GET
  public Collection<Person> getAllPeople(){
      Set<Person> allPeople = new HashSet<>();

try (Connection conn = defaultDataSource.getConnection();
	 ResultSet rs = conn.prepareStatement("SELECT name, age, id FROM people").executeQuery()){
	while (rs.next()) {
		allPeople.add(new Person(rs.getString("name"),rs.getInt("age"),rs.getLong("id")));
	}			
	return allPeople;
} catch (SQLException e) {
	e.printStackTrace(System.out);
} 
      throw new InternalServerErrorException("Could not get all people");  
  }
 
源代码18 项目: microshed-testing   文件: PersonServiceWithJDBC.java
@GET
  @Path("/{personId}")
  public Person getPerson(@PathParam("personId") long id) {
      try (Connection conn = defaultDataSource.getConnection();
	 ResultSet rs = conn.prepareStatement("SELECT name, age FROM people WHERE id = "+id).executeQuery()){
	if (rs.next()) {
		return new Person(rs.getString("name"),rs.getInt("age"),id);
	}			
	throw new NotFoundException("Person with id " + id + " not found.");
} catch (SQLException e) {
	e.printStackTrace(System.out);
}
throw new InternalServerErrorException("Could not get person");  
  }
 
@GET()
@Produces(MediaType.APPLICATION_JSON)
public CompletionStage<List<$Type$Output>> getResources_$name$() {
    return CompletableFuture.supplyAsync(() -> {
        return process.instances().values().stream()
                .map(pi -> mapOutput(new $Type$Output(), pi.variables()))
             .collect(Collectors.toList());
    });   
}
 
源代码20 项目: sofa-registry   文件: RenewSwitchResource.java
/**
 * 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;
}
 
源代码21 项目: micro-integrator   文件: MusicRestService.java
@GET
@Path("/get_singer_details")
@Produces(MediaType.APPLICATION_JSON)
public Singer getSingerDetailsInJSON(@QueryParam("singer") final String singerName) {
    /*            Music music = new Music();
   music.setAlbum("Beat It !!!");
   music.setSinger("Micheal Jackson");*/

    return musicService.getBySinger(singerName);
    //return musicService.musicCollection.get("Dimuthu");

}
 
源代码22 项目: presto   文件: TaskResource.java
@ResourceSecurity(INTERNAL_ONLY)
@GET
@Path("{taskId}/results/{bufferId}/{token}/acknowledge")
public void acknowledgeResults(
        @PathParam("taskId") TaskId taskId,
        @PathParam("bufferId") OutputBufferId bufferId,
        @PathParam("token") final long token)
{
    requireNonNull(taskId, "taskId is null");
    requireNonNull(bufferId, "bufferId is null");

    taskManager.acknowledgeTaskResults(taskId, bufferId, token);
}
 
源代码23 项目: camel-quarkus   文件: CoreResource.java
@Path("/resources/{name : (.+)?}")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String getResource(@PathParam("name") String name) throws IOException {
    try (InputStream is = this.getClass().getClassLoader().getResourceAsStream(name)) {
        if (is == null) {
            return null;
        }
        return IOUtils.toString(is, StandardCharsets.UTF_8);
    }
}
 
源代码24 项目: camel-quarkus   文件: BindyResource.java
@Path("/jsonToCsv")
@GET
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String jsonToCsv(final CsvOrder order) {
    LOG.infof("Invoking  jsonToCsv: %s", order);
    return producerTemplate.requestBody("direct:jsonToCsv", order, String.class);
}
 
源代码25 项目: browserup-proxy   文件: EntriesProxyResource.java
@GET
@Path("/assertStatusEquals")
@Produces(MediaType.APPLICATION_JSON)
@Operation(description = "In case url pattern is provided assert that all responses found by url pattern have specified http status, " +
        "otherwise assert that all responses of current step have specified status.",
        responses = {@ApiResponse(
                description = "Assertion result",
                content = @Content(
                        mediaType = MediaType.APPLICATION_JSON,
                        schema = @Schema(implementation = AssertionResult.class)))})
public AssertionResult statusEquals(
        @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,

        @QueryParam(STATUS)
        @NotNullConstraint(paramName = STATUS)
        @HttpStatusCodeConstraint(paramName = STATUS)
        @Parameter(required = true, description = STATUS_DESCRIPTION) String status) {

    MitmProxyServer proxyServer = proxyManager.get(port);
    int intStatus = Integer.parseInt(status);

    return StringUtils.isEmpty(urlPattern) ?
            proxyServer.assertResponseStatusCode(intStatus) :
            proxyServer.assertResponseStatusCode(Pattern.compile(urlPattern), intStatus);
}
 
源代码26 项目: browserup-proxy   文件: EntriesProxyResource.java
@GET
@Path("/assertResponseTimeLessThanOrEqual")
@Produces(MediaType.APPLICATION_JSON)
@Operation(
        description = "Assert that the response times for all requests " +
                "found by a given URL pattern are less than or equal to a given number of milliseconds.",
        responses = {
                @ApiResponse(
                        description = "Assertion result",
                        content = @Content(
                                mediaType = MediaType.APPLICATION_JSON,
                                schema = @Schema(implementation = AssertionResult.class)))})
public AssertionResult responseTimeLessThanOrEqual(
        @PathParam(PORT)
        @NotNullConstraint(paramName = PORT)
        @PortWithExistingProxyConstraint
        @Parameter(required = true, in = ParameterIn.PATH, description = DocConstants.PORT_DESCRIPTION) int port,

        @QueryParam(URL_PATTERN)
        @NotBlankConstraint(paramName = URL_PATTERN)
        @PatternConstraint(paramName = URL_PATTERN)
        @Parameter(required = true, description = DocConstants.URL_PATTERN_DESCRIPTION) String urlPattern,

        @QueryParam(MILLISECONDS)
        @LongPositiveConstraint(value = 0, paramName = MILLISECONDS)
        @Parameter(required = true, description = DocConstants.MILLISECONDS_DESCRIPTION) String milliseconds) {

    return proxyManager.get(port).assertResponseTimeLessThanOrEqual(
            Pattern.compile(urlPattern),
            Long.parseLong(milliseconds));
}
 
源代码27 项目: camel-quarkus   文件: HttpResource.java
@Path("/http/get")
@GET
@Produces(MediaType.TEXT_PLAIN)
public String httpGet(@QueryParam("test-port") int port) {
    return producerTemplate
            .to("http://localhost:" + port + "/service/get?bridgeEndpoint=true")
            .withHeader(Exchange.HTTP_METHOD, "GET")
            .request(String.class);
}
 
源代码28 项目: quarkus-deep-dive   文件: AsyncResource.java
@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);
}
 
源代码29 项目: apicurio-registry   文件: Api.java
@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);
}
 
源代码30 项目: presto   文件: TaskResource.java
@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);
}
 
 类所在包
 同包方法