下面列出了怎么用javax.ws.rs.GET的API类实例代码及写法,或者点击链接到github查看源代码。
@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();
}
}
@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();
}
}
@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;
}
@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();
}
@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();
}
}
@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();
}
@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);
}
}
@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();
}
@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();
}
@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));
}
@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();
}
@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;
}
@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();
}
@GET
@Path("/stream")
@Produces(MediaType.SERVER_SENT_EVENTS)
public Publisher<String> stream() {
return ReactiveStreams.of("a", "b", "c")
.map(String::toUpperCase)
.buildRs();
}
@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;
}
@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)' }");
}
}
@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");
}
@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());
});
}
/**
* 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;
}
@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");
}
@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);
}
@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);
}
}
@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);
}
@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);
}
@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));
}
@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);
}
@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);
}
@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);
}
@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);
}