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 |
@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: StramWebServices.java From Bats with Apache License 2.0 | 6 votes |
@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 #3
Source File: Application.java From camel-k-runtime with Apache License 2.0 | 6 votes |
@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 #4
Source File: MetricsResource.java From metrics with Apache License 2.0 | 6 votes |
@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 #5
Source File: SetsResource.java From cantor with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 #6
Source File: ExperimentRestApi.java From submarine with Apache License 2.0 | 6 votes |
@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 #7
Source File: QueryResource.java From presto with Apache License 2.0 | 6 votes |
@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 #8
Source File: TestingHttpBackupResource.java From presto with Apache License 2.0 | 6 votes |
@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 #9
Source File: UserResource.java From hmdm-server with Apache License 2.0 | 6 votes |
@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 #10
Source File: SetsResource.java From cantor with BSD 3-Clause "New" or "Revised" License | 6 votes |
@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 #11
Source File: OAuthResource.java From clouditor with Apache License 2.0 | 5 votes |
@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 #12
Source File: TaskResource.java From osgi-best-practices with Apache License 2.0 | 5 votes |
@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(); }
Example #13
Source File: AsyncResource.java From quarkus-deep-dive with Apache License 2.0 | 5 votes |
@GET @Path("/stream") @Produces(MediaType.SERVER_SENT_EVENTS) public Publisher<String> stream() { return ReactiveStreams.of("a", "b", "c") .map(String::toUpperCase) .buildRs(); }
Example #14
Source File: AccountsResource.java From clouditor with Apache License 2.0 | 5 votes |
@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; }
Example #15
Source File: FilesResource.java From hmdm-server with Apache License 2.0 | 5 votes |
@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(); } }
Example #16
Source File: ProfileResources.java From Bats with Apache License 2.0 | 5 votes |
@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)' }"); } }
Example #17
Source File: PersonServiceWithJDBC.java From microshed-testing with Apache License 2.0 | 5 votes |
@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"); }
Example #18
Source File: PersonServiceWithJDBC.java From microshed-testing with Apache License 2.0 | 5 votes |
@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"); }
Example #19
Source File: ReactiveRestResourceTemplate.java From kogito-runtimes with Apache License 2.0 | 5 votes |
@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()); }); }
Example #20
Source File: RenewSwitchResource.java From sofa-registry with Apache License 2.0 | 5 votes |
/** * 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 #21
Source File: MusicRestService.java From micro-integrator with Apache License 2.0 | 5 votes |
@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"); }
Example #22
Source File: TaskResource.java From presto with Apache License 2.0 | 5 votes |
@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); }
Example #23
Source File: CoreResource.java From camel-quarkus with Apache License 2.0 | 5 votes |
@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); } }
Example #24
Source File: BindyResource.java From camel-quarkus with Apache License 2.0 | 5 votes |
@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); }
Example #25
Source File: EntriesProxyResource.java From browserup-proxy with Apache License 2.0 | 5 votes |
@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); }
Example #26
Source File: EntriesProxyResource.java From browserup-proxy with Apache License 2.0 | 5 votes |
@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)); }
Example #27
Source File: HttpResource.java From camel-quarkus with Apache License 2.0 | 5 votes |
@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); }
Example #28
Source File: AsyncResource.java From quarkus-deep-dive with Apache License 2.0 | 5 votes |
@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 #29
Source File: Api.java From apicurio-registry with Apache License 2.0 | 5 votes |
@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 #30
Source File: TaskResource.java From presto with Apache License 2.0 | 5 votes |
@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); }