@PUT @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @ApiOperation(value = "Install Presto using rpm or tarball") @ApiResponses(value = { @ApiResponse(code = 207, message = "Multiple responses available"), @ApiResponse(code = 400, message = "Request contains invalid parameters")}) public Response install(String urlToFetchPackage, @QueryParam("checkDependencies") @DefaultValue("true") boolean checkDependencies, @QueryParam("scope") String scope, @QueryParam("nodeId") List<String> nodeId) { ApiRequester.Builder apiRequester = requesterBuilder(ControllerPackageAPI.class) .httpMethod(PUT) .accept(MediaType.TEXT_PLAIN) .entity(Entity.entity(urlToFetchPackage, MediaType.TEXT_PLAIN)); optionalQueryParam(apiRequester, "checkDependencies", checkDependencies); return forwardRequest(scope, apiRequester.build(), nodeId); }
@POST @Consumes(MediaType.TEXT_PLAIN) @Produces(MediaType.TEXT_PLAIN) @ApiOperation(value = "Upgrade Presto") @ApiResponses(value = { @ApiResponse(code = 207, message = "Multiple responses available"), @ApiResponse(code = 400, message = "Request contains invalid parameters")}) public Response upgrade(String urlToFetchPackage, @QueryParam("checkDependencies") @DefaultValue("true") boolean checkDependencies, @QueryParam("forceUpgrade") @DefaultValue("false") boolean forceUpgrade, @QueryParam("preserveConfig") @DefaultValue("true") boolean preserveConfig, @QueryParam("scope") String scope, @QueryParam("nodeId") List<String> nodeId) { ApiRequester.Builder apiRequester = requesterBuilder(ControllerPackageAPI.class) .httpMethod(POST) .accept(MediaType.TEXT_PLAIN) .entity(Entity.entity(urlToFetchPackage, MediaType.TEXT_PLAIN)); optionalQueryParam(apiRequester, "checkDependencies", checkDependencies); optionalQueryParam(apiRequester, "preserveConfig", preserveConfig); optionalQueryParam(apiRequester, "forceUpgrade", forceUpgrade); return forwardRequest(scope, apiRequester.build(), nodeId); }
@Path("snapshot") @GET @Produces(MediaType.APPLICATION_JSON) public Response getJobSnapshot( @DefaultValue("1") @QueryParam("depth") int maximumDepth, @DefaultValue("true") @QueryParam("static") boolean includeStaticAttributes) throws StreamsTrackerException, WebApplicationException { StreamsInstanceTracker jobTracker = StreamsInstanceTracker .getInstance(); String snapshot = null; snapshot = jobTracker.getJobSnapshot(ji.getId().intValue(), maximumDepth, includeStaticAttributes); if (snapshot == null) { throw new WebApplicationException("Job " + ji.getId() + " returned an empty snapshot.", Response.Status.NO_CONTENT); // 204 } return Response.status(200).entity(snapshot).build(); }
@GET @Produces(MediaType.APPLICATION_JSON) public SourceUI getSource(@QueryParam("includeContents") @DefaultValue("true") boolean includeContents) throws Exception { try { final SourceConfig config = namespaceService.get().getSource(sourcePath.toNamespaceKey()); final SourceState sourceState = sourceService.getSourceState(sourcePath.getSourceName().getName()); if (sourceState == null) { throw new SourceNotFoundException(sourcePath.getSourceName().getName()); } final SourceUI source = newSource(config) .setNumberOfDatasets(namespaceService.get().getAllDatasetsCount(new NamespaceKey(config.getName()))); source.setState(sourceState); if (includeContents) { source.setContents(sourceService.listSource(sourcePath.getSourceName(), namespaceService.get().getSource(sourcePath.toNamespaceKey()), securityContext.getUserPrincipal().getName())); } return source; } catch (NamespaceNotFoundException nfe) { throw new SourceNotFoundException(sourcePath.getSourceName().getName(), nfe); } }
@PUT @Produces(MediaType.APPLICATION_OCTET_STREAM) @Consumes(MediaType.APPLICATION_OCTET_STREAM) public void setZNodeAsOctet(@PathParam("path") String path, @DefaultValue("-1") @QueryParam("version") String versionParam, @DefaultValue("false") @QueryParam("null") String setNull, @Context UriInfo ui, byte[] data) throws InterruptedException, KeeperException { ensurePathNotNull(path); int version; try { version = Integer.parseInt(versionParam); } catch (NumberFormatException e) { throw new WebApplicationException(Response.status( Response.Status.BAD_REQUEST).entity( new ZError(ui.getRequestUri().toString(), path + " bad version " + versionParam)).build()); } if (setNull.equals("true")) { data = null; } zk.setData(path, data, version); }
@DELETE @Produces( { MediaType.APPLICATION_JSON, "application/javascript", MediaType.APPLICATION_XML, MediaType.APPLICATION_OCTET_STREAM }) public void deleteZNode(@PathParam("path") String path, @DefaultValue("-1") @QueryParam("version") String versionParam, @Context UriInfo ui) throws InterruptedException, KeeperException { ensurePathNotNull(path); int version; try { version = Integer.parseInt(versionParam); } catch (NumberFormatException e) { throw new WebApplicationException(Response.status( Response.Status.BAD_REQUEST).entity( new ZError(ui.getRequestUri().toString(), path + " bad version " + versionParam)).build()); } zk.delete(path, version); }
@POST @Path("/plans/{plan}/{sync:sync|async}") @Consumes({ MediaType.MULTIPART_FORM_DATA }) public Response annotate_POST_MULTIPART( @Context ServletContext servletContext, @Context HttpContext httpContext, @PathParam("plan") String planName, @PathParam("sync") String sync, @FormDataParam("text") @DefaultValue("") String text, @FormDataParam("sourcedb") @DefaultValue("") String sourcedb, @FormDataParam("sourceid") @DefaultValue("") String sourceid, FormDataMultiPart formData ) throws Exception { return annotate(servletContext, httpContext, planName, text, sourcedb, sourceid, null, formData, sync.equals("async")); }
@GET @Path("/folder/{path: .*}") @Produces(MediaType.APPLICATION_JSON) public Folder getFolder(@PathParam("path") String path, @QueryParam("includeContents") @DefaultValue("true") boolean includeContents) throws Exception { FolderPath folderPath = FolderPath.fromURLPath(homeName, path); try { final FolderConfig folderConfig = namespaceService.getFolder(folderPath.toNamespaceKey()); final List<NamespaceKey> datasetPaths = namespaceService.getAllDatasets(folderPath.toNamespaceKey()); final ExtendedConfig extendedConfig = new ExtendedConfig().setDatasetCount((long)datasetPaths.size()) .setJobCount(datasetService.getJobsCount(datasetPaths)); folderConfig.setExtendedConfig(extendedConfig); NamespaceTree contents = includeContents ? newNamespaceTree(namespaceService.list(folderPath.toNamespaceKey())) : null; return newFolder(folderPath, folderConfig, contents); } catch (NamespaceNotFoundException nfe) { throw new FolderNotFoundException(folderPath, nfe); } }
@GET @Path("/{file}") @Produces(MediaType.APPLICATION_JSON) @ApiOperation(value = "Get Presto log file") @ApiResponses(value = { @ApiResponse(code = 200, message = "Retrieved logs"), @ApiResponse(code = 400, message = "Invalid parameters"), @ApiResponse(code = 404, message = "Resource not found")}) public Response getLog( @PathParam("file") @ApiParam("The name of a file") String file, @QueryParam("from") @ApiParam("Ignore logs before this date") Instant fromDate, @QueryParam("to") @ApiParam("Ignore logs after this date") Instant toDate, @QueryParam("level") @ApiParam("Only get logs of this level") @DefaultValue(LogsHandler.DEFAULT_LOG_LEVEL) String level, @QueryParam("n") @ApiParam("The maximum number of log entries to get") Integer maxEntries) { return logsHandler.getLogs(file, fromDate, toDate, level, maxEntries); }
@JsonCreator public Space( @JsonProperty("id") @DefaultValue("null") String id, // default is null for new spaces @JsonProperty("name") String name, @JsonProperty("description") String description, @JsonProperty("version") Long version, @JsonProperty("contents") NamespaceTree contents, @JsonProperty("datasetCount") int datasetCount, @JsonProperty("ctime") Long ctime ) { checkArgument(!isNullOrEmpty(name), "space name can not be empty"); this.id = id; this.name = name; this.description = description; this.version = version; this.contents = contents; this.datasetCount = datasetCount; this.ctime = ctime; }
@Override @SuppressWarnings("unchecked") public T get() { final MinijaxRequestContext context = MinijaxRequestContext.getThreadLocal(); final Class<?> c = key.getType(); final MinijaxForm form = context.getForm(); final String name = key.getName(); if (c == InputStream.class) { return form == null ? null : (T) form.getInputStream(name); } if (c == Part.class) { return form == null ? null : (T) form.getPart(name); } String value = form == null ? null : form.getString(name); final DefaultValue defaultValue = key.getDefaultValue(); if (value == null && defaultValue != null) { value = defaultValue.value(); } return (T) context.getApplication().convertParamToType(value, c, key.getAnnotations()); }
/** Handle HTTP DELETE request for the root. */ @DELETE @Path("/") @Produces(MediaType.APPLICATION_JSON) public Response deleteRoot( @Context final UserGroupInformation ugi, @QueryParam(DelegationParam.NAME) @DefaultValue(DelegationParam.DEFAULT) final DelegationParam delegation, @QueryParam(UserParam.NAME) @DefaultValue(UserParam.DEFAULT) final UserParam username, @QueryParam(DoAsParam.NAME) @DefaultValue(DoAsParam.DEFAULT) final DoAsParam doAsUser, @QueryParam(DeleteOpParam.NAME) @DefaultValue(DeleteOpParam.DEFAULT) final DeleteOpParam op, @QueryParam(RecursiveParam.NAME) @DefaultValue(RecursiveParam.DEFAULT) final RecursiveParam recursive, @QueryParam(SnapshotNameParam.NAME) @DefaultValue(SnapshotNameParam.DEFAULT) final SnapshotNameParam snapshotName ) throws IOException, InterruptedException { return delete(ugi, delegation, username, doAsUser, ROOT, op, recursive, snapshotName); }
@DELETE @Path("/{uuid}") @ApiOperation("Delete a group") public Response deleteGroup( // @formatter:off @ApiParam(APIDOC_GROUPUUID) @PathParam("uuid") String uuid, @ApiParam(value = "also delete subgroups", allowableValues = "true,false", defaultValue = "true", required = false) @QueryParam("cascade") @DefaultValue("false") Boolean deleteSubgroups // @formatter:on ) { boolean deleteSub = (deleteSubgroups == null ? false : deleteSubgroups); // ensure group exists, else throw 404 TLEGroup tleGroup = tleGroupService.get(uuid); if( tleGroup == null ) { return Response.status(Status.NOT_FOUND).build(); } tleGroupService.delete(uuid, deleteSub); return Response.status(Status.NO_CONTENT).build(); }
public ZNodeResource(@DefaultValue("") @QueryParam("session") String session, @Context UriInfo ui, @Context HttpServletRequest request ) throws IOException { String contextPath = request.getContextPath(); if (contextPath.equals("")) { contextPath = "/"; } if (session.equals("")) { session = null; } else if (!ZooKeeperService.isConnected(contextPath, session)) { throw new WebApplicationException(Response.status( Response.Status.UNAUTHORIZED).build()); } zk = ZooKeeperService.getClient(contextPath, session); }
@POST @Consumes(TEXT_PLAIN) @Produces(TEXT_PLAIN) @ApiOperation(value = "Upgrade Presto") @ApiResponses(value = { @ApiResponse(code = 202, message = "Acknowledged request"), @ApiResponse(code = 400, message = "Invalid url"), @ApiResponse(code = 409, message = "Presto is running. Please stop Presto before beginning upgrade.") }) public synchronized Response upgrade(@ApiParam("Url to fetch package") String packageUrl, @QueryParam("checkDependencies") @DefaultValue("true") @ApiParam("If false, disables dependency checking") boolean checkDependencies, @QueryParam("preserveConfig") @DefaultValue("true") @ApiParam("If false, config files are not preserved") boolean preserveConfig, @QueryParam("forceUpgrade") @DefaultValue("false") @ApiParam("If true, warnings are ignored during upgrade") boolean forceUpgrade) { return controller.upgrade(packageUrl, checkDependencies, preserveConfig, forceUpgrade); }
@GET @Path("/features") @Produces(MediaType.APPLICATION_JSON) public FeatureCollection getFeatureCollection( @DefaultValue("") @QueryParam("devices") String devices, @DefaultValue("-1") @QueryParam("startTime") long startTime, @DefaultValue("-1") @QueryParam("endTime") long endTime, @DefaultValue("point") @QueryParam("type") String type) throws IOException, IllegalArgumentException, IllegalAccessException { FeatureCollection features = new FeatureCollection(); String[] deviceIds = devices.split(","); for (String deviceId : deviceIds) { if (!deviceId.isEmpty()) { Iterable<MAVLinkRecord> records = stream.query( deviceId, startTime > 0 ? new Date(startTime) : null, endTime > 0 ? new Date(endTime) : null, MAVLINK_MSG_ID_HIGH_LATENCY); if (type.equalsIgnoreCase("point")) { buildPointFeatures(features, records); } else if (type.equalsIgnoreCase("linestring")) { buildLineFeatures(features, deviceId, records); } } } return features; }
@GET @Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON}) public List<IDCount> get(@DefaultValue("10") @QueryParam("howMany") int howMany, @DefaultValue("0") @QueryParam("offset") int offset, @QueryParam("rescorerParams") List<String> rescorerParams) throws OryxServingException { ALSServingModel model = getALSServingModel(); RescorerProvider rescorerProvider = model.getRescorerProvider(); Rescorer rescorer = null; if (rescorerProvider != null) { rescorer = rescorerProvider.getMostActiveUsersRescorer(rescorerParams); } return MostPopularItems.mapTopCountsToIDCounts( model.getUserCounts(), howMany, offset, rescorer); }
@POST @Path("/stop") @ApiOperation(value = "Stop Presto") @ApiResponses(value = { @ApiResponse(code = 200, message = "Successfully stopped Presto"), @ApiResponse(code = 404, message = "Presto is not installed"), @ApiResponse(code = 409, message = "Coordinator can't be gracefully stopped")}) public synchronized Response stopPresto(@QueryParam("stopType") @ApiParam("StopType: TERMINATE, KILL or GRACEFUL") @DefaultValue("GRACEFUL") StopType stopType) { return controller.stop(stopType); }
@GET @Path("/{nickname}/claim-qr") @Produces("image/png") public Response directClaimLinkQrCode( @PathParam("nickname") final String nickname, @QueryParam("baseUrl") @DefaultValue(DEFAULT_BASE_URL) final String baseUrl ) throws IOException { final byte[] claimQr = qrCodeAsPng(baseUrl, nickname, "?claim=true"); return Response.ok(new ByteArrayInputStream(claimQr)).build(); }
@GET @Path("/{id:\\d+}/sticker") @Produces("image/png") public Response showSticker( @PathParam("id") final Long id, @QueryParam("baseUrl") @DefaultValue(DEFAULT_BASE_URL) final String baseUrl ) throws IOException { final Device device = deviceRepo.findById(id); return sticker(baseUrl, device); }
private Key( final Class<T> type, final Annotation[] annotations, final Strategy strategy, final Class<? extends Annotation> qualifier, final String name, final DefaultValue defaultValue) { this.type = type; this.annotations = annotations; this.strategy = strategy; this.qualifier = qualifier; this.name = name; this.defaultValue = defaultValue; }
@POST @javax.ws.rs.Path("/commands/{commandName}/validate") @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) public JsonObject validateCommand(JsonObject content, @PathParam("commandName") @DefaultValue(DEFAULT_COMMAND_NAME) String commandName, @Context HttpHeaders headers) throws Exception { validateCommand(commandName); JsonObjectBuilder builder = createObjectBuilder(); try (CommandController controller = getCommand(commandName, ForgeInitializer.getRoot(), headers)) { controller.getContext().getAttributeMap().put("action", "validate"); helper.populateController(content, controller); int stepIndex = content.getInt("stepIndex", 1); if (controller instanceof WizardCommandController) { WizardCommandController wizardController = (WizardCommandController) controller; for (int i = 0; i < stepIndex; i++) { wizardController.next().initialize(); helper.populateController(content, wizardController); } } helper.describeValidation(builder, controller); helper.describeInputs(builder, controller); helper.describeCurrentState(builder, controller); } return builder.build(); }
@POST @Path("/annotate-nif") public Response annotateNif(String request, @QueryParam("q") String q, @QueryParam("annotator") @DefaultValue("default") String annotator, @QueryParam("google-cse-id") String cseId, @QueryParam("google-api-key") String apiKey, @QueryParam("exclude-s2") String excludeS2) { if (q == null) return Response.serverError().entity("Parameter q required.").build(); if (cseId == null) return Response.serverError().entity("Parameter google-cse-id required.").build(); if (apiKey == null) return Response.serverError().entity("Parameter google-api-key required.").build(); SmaphConfig c = getSmaphConfig(cseId, apiKey); return Response.ok(encodeResponseNif(request, getAnnotatorByName(annotator, excludeS2 != null, c))).build(); }
@GET @Path("/annotate") @Produces({ MediaType.APPLICATION_JSON }) public Response annotateDefault(@QueryParam("q") String q, @QueryParam("annotator") @DefaultValue("default") String annotator, @QueryParam("google-cse-id") String cseId, @QueryParam("google-api-key") String apiKey, @QueryParam("exclude-s2") String excludeS2) { if (q == null) return Response.serverError().entity("Parameter q required.").build(); if (cseId == null) return Response.serverError().entity("Parameter google-cse-id required.").build(); if (apiKey == null) return Response.serverError().entity("Parameter google-api-key required.").build(); SmaphConfig c = getSmaphConfig(cseId, apiKey); SmaphAnnotator ann = getAnnotatorByName(annotator, excludeS2 != null, c); return Response.ok(encodeResponseJson(ann.solveSa2W(q), ann)).build(); }
/** * Apply an ephemeral transformation and see the result (note that this does not create a dataset version). Result * includes preview (sampled) output, highlighted/deleted columns and marked rows. * * @param transform * @return * @throws DatasetVersionNotFoundException * @throws NamespaceException * @throws DatasetNotFoundException */ @POST @Path("transformPeek") @Produces(APPLICATION_JSON) @Consumes(APPLICATION_JSON) public InitialPendingTransformResponse transformDataSetPreview( /* Body */ TransformBase transform, @QueryParam("newVersion") DatasetVersion newVersion, @QueryParam("limit") @DefaultValue("50") int limit) throws DatasetVersionNotFoundException, DatasetNotFoundException, NamespaceException { final VirtualDatasetUI virtualDatasetUI = getDatasetConfig(); checkNotNull(virtualDatasetUI.getState()); return transformer.transformPreviewWithExecute(newVersion, datasetPath, virtualDatasetUI, transform, limit); }
@GET @Path("{" + PATH + ":.*}") @Produces({MediaType.APPLICATION_JSON}) public Response get( @PathParam(PATH) @DefaultValue("UNKNOWN_" + PATH) final String path, @QueryParam(OP) @DefaultValue("UNKNOWN_" + OP) final String op ) throws IOException { LOG.info("get: " + PATH + "=" + path + ", " + OP + "=" + op); final Map<String, Object> m = new TreeMap<String, Object>(); m.put(PATH, path); m.put(OP, op); final String js = JSON.toString(m); return Response.ok(js).type(MediaType.APPLICATION_JSON).build(); }
@GET @Path("/find") @Produces(MediaType.APPLICATION_JSON) public Response find( @QueryParam("wildcards") @DefaultValue("0") IntParam wildcardsParam, @QueryParam("from") @DefaultValue("-1") IntParam fromParam, @QueryParam("until") @DefaultValue("-1") IntParam untilParam, @QueryParam("position") @DefaultValue("-1") IntParam positionParam, @QueryParam("format") @DefaultValue("treejson") String format, @QueryParam("query") String query) { final boolean wildcards = (wildcardsParam.get().equals(1)); final int fromTime = fromParam.get(); final int untilTime = untilParam.get(); final int nodePosition = positionParam.get(); final Map<String, String> errors = new HashMap<>(); if (!VALID_FORMATS.contains(format)) { errors.put("format", String.format("unrecognized format: \"%s\".", format)); } if (query == null || query.isEmpty()) { errors.put("query", "this parameter is required."); } if (!errors.isEmpty()) { final Response response = Response .status(Response.Status.BAD_REQUEST) .entity(ImmutableMap.of("errors", errors)) .type(MediaType.APPLICATION_JSON).build(); throw new WebApplicationException(response); } return Response.noContent().build(); }
@GET @Produces( { MediaType.APPLICATION_JSON, "application/javascript" }) public Response getZNodeListJSON( @PathParam("path") String path, @QueryParam("callback") String callback, @DefaultValue("data") @QueryParam("view") String view, @DefaultValue("base64") @QueryParam("dataformat") String dataformat, @Context UriInfo ui) throws InterruptedException, KeeperException { return getZNodeList(true, path, callback, view, dataformat, ui); }
@GET @Produces(MediaType.APPLICATION_XML) public Response getZNodeList( @PathParam("path") String path, @QueryParam("callback") String callback, @DefaultValue("data") @QueryParam("view") String view, @DefaultValue("base64") @QueryParam("dataformat") String dataformat, @Context UriInfo ui) throws InterruptedException, KeeperException { return getZNodeList(false, path, callback, view, dataformat, ui); }
@PUT @Produces( { MediaType.APPLICATION_JSON, "application/javascript", MediaType.APPLICATION_XML }) @Consumes(MediaType.APPLICATION_OCTET_STREAM) public Response setZNode( @PathParam("path") String path, @QueryParam("callback") String callback, @DefaultValue("-1") @QueryParam("version") String versionParam, @DefaultValue("base64") @QueryParam("dataformat") String dataformat, @DefaultValue("false") @QueryParam("null") String setNull, @Context UriInfo ui, byte[] data) throws InterruptedException, KeeperException { ensurePathNotNull(path); int version; try { version = Integer.parseInt(versionParam); } catch (NumberFormatException e) { throw new WebApplicationException(Response.status( Response.Status.BAD_REQUEST).entity( new ZError(ui.getRequestUri().toString(), path + " bad version " + versionParam)).build()); } if (setNull.equals("true")) { data = null; } Stat stat = zk.setData(path, data, version); ZStat zstat = new ZStat(path, ui.getAbsolutePath().toString(), null, null, stat.getCzxid(), stat.getMzxid(), stat.getCtime(), stat .getMtime(), stat.getVersion(), stat.getCversion(), stat.getAversion(), stat.getEphemeralOwner(), stat .getDataLength(), stat.getNumChildren(), stat .getPzxid()); return Response.status(Response.Status.OK).entity( new JSONWithPadding(zstat, callback)).build(); }
@GET public Response getAllPosts( @QueryParam("q") String q, @QueryParam("limit") @DefaultValue("10") int limit, @QueryParam("offset") @DefaultValue("0") int offset ) { return Response.ok(this.posts.findByKeyword(q, limit, offset)).build(); }
@GET @Produces({ Constants.MIMETYPE_PROTOBUF, Constants.MIMETYPE_PROTOBUF_IETF }) public Response getProtobuf( final @Context UriInfo uriInfo, final @PathParam("scanspec") String scanSpec, final @HeaderParam("Accept") String contentType, @DefaultValue(Integer.MAX_VALUE + "") @QueryParam(Constants.SCAN_LIMIT) int userRequestedLimit, @DefaultValue("") @QueryParam(Constants.SCAN_START_ROW) String startRow, @DefaultValue("") @QueryParam(Constants.SCAN_END_ROW) String endRow, @DefaultValue("column") @QueryParam(Constants.SCAN_COLUMN) List<String> column, @DefaultValue("1") @QueryParam(Constants.SCAN_MAX_VERSIONS) int maxVersions, @DefaultValue("-1") @QueryParam(Constants.SCAN_BATCH_SIZE) int batchSize, @DefaultValue("0") @QueryParam(Constants.SCAN_START_TIME) long startTime, @DefaultValue(Long.MAX_VALUE + "") @QueryParam(Constants.SCAN_END_TIME) long endTime, @DefaultValue("true") @QueryParam(Constants.SCAN_BATCH_SIZE) boolean cacheBlocks) { servlet.getMetrics().incrementRequests(1); try { int fetchSize = this.servlet.getConfiguration().getInt(Constants.SCAN_FETCH_SIZE, 10); ProtobufStreamingUtil stream = new ProtobufStreamingUtil(this.results, contentType, userRequestedLimit, fetchSize); servlet.getMetrics().incrementSucessfulScanRequests(1); ResponseBuilder response = Response.ok(stream); response.header("content-type", contentType); return response.build(); } catch (Exception exp) { servlet.getMetrics().incrementFailedScanRequests(1); processException(exp); LOG.warn(exp); return null; } }
@GET @Path("{userID}/{itemID}") @Produces({MediaType.TEXT_PLAIN, "text/csv", MediaType.APPLICATION_JSON}) public List<IDValue> get( @PathParam("userID") String userID, @PathParam("itemID") String itemID, @DefaultValue("10") @QueryParam("howMany") int howMany, @DefaultValue("0") @QueryParam("offset") int offset) throws OryxServingException { check(howMany > 0, "howMany must be positive"); check(offset >= 0, "offset must be non-negative"); ALSServingModel model = getALSServingModel(); float[] itemVector = model.getItemVector(itemID); checkExists(itemVector != null, itemID); List<Pair<String,float[]>> knownItemVectors = model.getKnownItemVectorsForUser(userID); if (knownItemVectors == null || knownItemVectors.isEmpty()) { return Collections.emptyList(); } double itemVectorNorm = VectorMath.norm(itemVector); Stream<Pair<String,Double>> idSimilarities = knownItemVectors.stream().map(itemIDVector -> { float[] otherItemVector = itemIDVector.getSecond(); double cosineSimilarity = VectorMath.cosineSimilarity(otherItemVector, itemVector, itemVectorNorm); return new Pair<>(itemIDVector.getFirst(), cosineSimilarity); }); return toIDValueResponse(idSimilarities.sorted(Pairs.orderBySecond(Pairs.SortOrder.DESCENDING)), howMany, offset); }
@GET @Path("/{file}") @Produces(MediaType.TEXT_PLAIN) @ApiOperation(value = "Get Presto log file") @ApiResponses(value = { @ApiResponse(code = 207, message = "Multiple responses available"), @ApiResponse(code = 400, message = "Request contains invalid parameters")}) public Response getLog( @PathParam("file") String file, @QueryParam("from") Instant fromDate, @QueryParam("to") Instant toDate, @QueryParam("level") @DefaultValue("ALL") String level, @QueryParam("n") Integer maxEntries, @QueryParam("scope") String scope, @QueryParam("nodeId") List<String> nodeId) { ApiRequester.Builder apiRequester = requesterBuilder(ControllerLogsAPI.class) .httpMethod(GET) .accept(MediaType.TEXT_PLAIN) .pathMethod("getLog") .resolveTemplate("file", file); optionalQueryParam(apiRequester, "from", fromDate); optionalQueryParam(apiRequester, "to", toDate); optionalQueryParam(apiRequester, "level", level); optionalQueryParam(apiRequester, "n", maxEntries); return forwardRequest(scope, apiRequester.build(), nodeId); }
@POST @Path("/plans/{plan}/{sync:sync|async}") @Consumes({ MediaType.APPLICATION_FORM_URLENCODED }) public Response annotate_POST_URLENCODED( @Context ServletContext servletContext, @Context HttpContext httpContext, @PathParam("plan") String planName, @PathParam("sync") String sync, @FormParam("text") @DefaultValue("") String text, @FormParam("sourcedb") @DefaultValue("") String sourcedb, @FormParam("sourceid") @DefaultValue("") String sourceid, MultivaluedMap<String,String> formParams ) throws Exception { return annotate(servletContext, httpContext, planName, text, sourcedb, sourceid, formParams, null, sync.equals("async")); }
@GET @Path("/{id}/output") public Response output( @PathParam("id") String id, @DefaultValue("false") @QueryParam("recdir") boolean recdir ) throws IOException, SAXException, ClassNotFoundException, InstantiationException, IllegalAccessException { return output(id, "", recdir ? Integer.MAX_VALUE : 1); }
@GET @Path("/{id}/output/{path:.*}") public Response output( @PathParam("id") String id, @PathParam("path") String path, @DefaultValue("false") @QueryParam("recdir") boolean recdir ) throws IOException, SAXException, ClassNotFoundException, InstantiationException, IllegalAccessException { return output(id, path, recdir ? Integer.MAX_VALUE : 1); }
@GET @Produces("image/png") public InputStream view(@QueryParam("id") String id, @QueryParam("width") @DefaultValue("16") int width) throws Exception { if (StringUtils.isBlank(id)) { logger.info("id cannot be blank"); return null; } if (id.indexOf("_") != -1) { String text = id; logger.info("process : {}", text); int index = text.indexOf("_"); int nextIndex = text.indexOf("x"); id = text.substring(0, index); width = Integer.parseInt(text.substring(index + 1, nextIndex)); logger.info("id : {}, width : {}", id, width); } logger.debug("width : {}", width); String tenantId = tenantHolder.getTenantId(); Long longId = null; try { longId = Long.parseLong(id); } catch (Exception ex) { logger.error(ex.getMessage(), ex); } return userAvatarService.viewAvatarById(longId, width, tenantId) .getInputStream(); }