@GET @Path("/{id}") @ApiOperation(value = "Get all properties of a node", response = Graph.class) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) @Produces({MediaType.APPLICATION_JSON, CustomMediaTypes.APPLICATION_GRAPHSON, MediaType.APPLICATION_XML, CustomMediaTypes.APPLICATION_GRAPHML, CustomMediaTypes.APPLICATION_XGMML, CustomMediaTypes.TEXT_GML, CustomMediaTypes.TEXT_CSV, CustomMediaTypes.TEXT_TSV, CustomMediaTypes.IMAGE_JPEG, CustomMediaTypes.IMAGE_PNG}) public Object getNode( @ApiParam(value = DocumentationStrings.GRAPH_ID_DOC, required = true) @PathParam("id") String id, @ApiParam(value = DocumentationStrings.PROJECTION_DOC, required = false) @QueryParam("project") @DefaultValue("*") Set<String> projection, @ApiParam(value = DocumentationStrings.JSONP_DOC, required = false) @QueryParam("callback") String callback) { return getNeighbors(id, new IntParam("0"), new BooleanParam("false"), Optional.<String>empty(), null, new BooleanParam("false"), projection, callback); }
@GET public ItemsRepresentation query( @Context javax.ws.rs.core.UriInfo info, @QueryParam("offset") @DefaultValue("-1") IntParam _offset, @QueryParam("limit") @DefaultValue("-1") IntParam _limit) { int offset = _offset.get(); int limit = _limit.get(); if (offset == -1 || limit == -1) { offset = offset == -1 ? 0 : offset; limit = limit == -1 ? 10 : limit; throw new WebApplicationException( Response.seeOther(info.getRequestUriBuilder().queryParam("offset", offset) .queryParam("limit", limit).build()) .build() ); } return new ItemsRepresentation(itemsModel, offset, limit); }
@GET @Path("view") @Produces({MediaType.TEXT_HTML}) public ItemsView view(@Context javax.ws.rs.core.UriInfo info, @QueryParam("offset") @DefaultValue("-1") IntParam _offset, @DefaultValue("-1") @QueryParam("limit") IntParam _limit){ int offset = _offset.get(); int limit = _limit.get(); if (offset == -1 || limit == -1) { offset = offset == -1 ? 0 : offset; limit = limit == -1 ? 10 : limit; throw new WebApplicationException( Response.seeOther(info.getRequestUriBuilder().queryParam("offset", offset) .queryParam("limit", limit).build()) .build() ); } ItemsRepresentation representation = new ItemsRepresentation(itemsModel, offset, limit); // render the view return new ItemsView(representation); }
@GET @Path ("{subscription}/peek") @RequiresPermissions ("databus|poll|{subscription}") @Timed (name = "bv.emodb.databus.DatabusResource1.peek", absolute = true) @ApiOperation (value = "Peek operation.", notes = "Returns an List of Events.", response = Event.class ) public Response peek(@QueryParam ("partitioned") BooleanParam partitioned, @PathParam ("subscription") String subscription, @QueryParam ("limit") @DefaultValue ("10") IntParam limit, @QueryParam ("includeTags") @DefaultValue ("false") BooleanParam includeTags, @Authenticated Subject subject) { // For backwards compatibility with older clients only include tags if explicitly requested // (default is false). PeekOrPollResponseHelper helper = getPeekOrPollResponseHelper(includeTags.get()); Iterator<Event> events = getClient(partitioned).peek(subject, subscription, limit.get()); return Response.ok().entity(helper.asEntity(events)).build(); }
@GET @Path ("{subscription}/poll") @RequiresPermissions ("databus|poll|{subscription}") @ApiOperation (value = "poll operation.", notes = "Returns a Response.", response = Response.class ) public Response poll(@QueryParam ("partitioned") BooleanParam partitioned, @PathParam ("subscription") String subscription, @QueryParam ("ttl") @DefaultValue ("30") SecondsParam claimTtl, @QueryParam ("limit") @DefaultValue ("10") IntParam limit, @QueryParam ("ignoreLongPoll") @DefaultValue ("false") BooleanParam ignoreLongPoll, @QueryParam ("includeTags") @DefaultValue ("false") BooleanParam includeTags, @Context HttpServletRequest request, @Authenticated Subject subject) { // For backwards compatibility with older clients only include tags if explicitly requested // (default is false). PeekOrPollResponseHelper helper = getPeekOrPollResponseHelper(includeTags.get()); return _poller.poll(subject, getClient(partitioned), subscription, claimTtl.get(), limit.get(), request, ignoreLongPoll.get(), helper); }
@DELETE @Timed @UnitOfWork @Path("/{id}") public Response delete(@PathParam("id") IntParam id) { LogSession s = controller.getLogSession(); if (s != null && s.getId() == id.get()) { controller.setLogSession(null); } temperatureEntryDao.deleteAllBySessionId(id.get()); boolean result = sessionDao.delete(id.get()); if (result) return Response.ok(id.get()).build(); else return Response.serverError().build(); }
@GET @Path("/suggestions/{term}") @ApiOperation(value = "Suggest terms", notes = "Suggests terms based on a mispelled or mistyped term.", response = String.class, responseContainer = "List") @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Object suggestFromTerm( @ApiParam( value = "Mispelled term", required = true ) @PathParam("term") String term, @ApiParam( value = DocumentationStrings.RESULT_LIMIT_DOC, required = false ) @QueryParam("limit") @DefaultValue("1") IntParam limit) { List<String> suggestions = newArrayList(Iterables.limit(vocabulary.getSuggestions(term), limit.get())); return suggestions; }
@GET @Path("/{id}") public BlogPost getPost(@PathParam("id") IntParam id, @Context DSLContext create) { final Record4<Integer, String, DateTime, String[]> record = create .select(BLOG_POST.ID, BLOG_POST.BODY, BLOG_POST.CREATED_AT, arrayAgg(POST_TAG.TAG_NAME)) .from(BLOG_POST) .leftOuterJoin(POST_TAG) .on(BLOG_POST.ID.equal(POST_TAG.POST_ID)) .where(BLOG_POST.ID.equal(id.get())) .groupBy(BLOG_POST.ID, BLOG_POST.BODY, BLOG_POST.CREATED_AT) .fetchOne(); if (record == null) { throw new WebApplicationException(Response.Status.NOT_FOUND); } final Integer postId = record.value1(); final String text = record.value2(); final DateTime createdAt = record.value3(); final List<String> tags = Arrays.asList(record.value4()); return BlogPost.create(postId, text, createdAt, tags); }
/** * Get one or more IDs as a Google Protocol Buffer response * * @param agent * User Agent * @param count * Number of IDs to return * @return generated IDs */ @GET @Timed @Produces(ProtocolBufferMediaType.APPLICATION_PROTOBUF) @CacheControl(mustRevalidate = true, noCache = true, noStore = true) public SnowizardResponse getIdAsProtobuf( @HeaderParam(HttpHeaders.USER_AGENT) final String agent, @QueryParam("count") final Optional<IntParam> count) { final List<Long> ids = Lists.newArrayList(); if (count.isPresent()) { for (int i = 0; i < count.get().get(); i++) { ids.add(getId(agent)); } } else { ids.add(getId(agent)); } return SnowizardResponse.newBuilder().addAllId(ids).build(); }
@GET @Produces(MediaType.APPLICATION_JSON) public Response root( @QueryParam("wildcards") @DefaultValue("0") IntParam wildcards, @QueryParam("from") @DefaultValue("-1") IntParam from, @QueryParam("until") @DefaultValue("-1") IntParam until, @QueryParam("position") @DefaultValue("-1") IntParam position, @QueryParam("format") @DefaultValue("treejson") String format, @QueryParam("query") String query) { return find(wildcards, from, until, position, format, query); }
@POST @Produces(MediaType.APPLICATION_JSON) public Response rootPost( @QueryParam("wildcards") @DefaultValue("0") IntParam wildcards, @QueryParam("from") @DefaultValue("-1") IntParam from, @QueryParam("until") @DefaultValue("-1") IntParam until, @QueryParam("position") @DefaultValue("-1") IntParam position, @QueryParam("format") @DefaultValue("treejson") String format, @QueryParam("query") String query) { return find(wildcards, from, until, position, format, query); }
@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(); }
@POST @Path("/find") @Produces(MediaType.APPLICATION_JSON) public Response findPost( @QueryParam("wildcards") @DefaultValue("0") IntParam wildcards, @QueryParam("from") @DefaultValue("-1") IntParam from, @QueryParam("until") @DefaultValue("-1") IntParam until, @QueryParam("position") @DefaultValue("-1") IntParam position, @QueryParam("format") @DefaultValue("treejson") String format, @QueryParam("query") String query) { return find(wildcards, from, until, position, format, query); }
private IndexSizePagination setUpPagination(@QueryParam(IndexSizePagination.INDEX_PARAM) Optional<IntegerParam> pageIndex, @QueryParam(IndexSizePagination.SIZE_PARAM) Optional<IntegerParam> pageSize, String indexName) { IndexSizePagination pagination = new IndexSizePagination(pageIndex.map(IntParam::get), pageSize.map(IntParam::get), register.getTotalDerivationRecords(indexName)); if (pagination.hasNextPage()) { httpServletResponseAdapter.addLinkHeader("next", pagination.getNextPageLink()); } if (pagination.hasPreviousPage()) { httpServletResponseAdapter.addLinkHeader("previous", pagination.getPreviousPageLink()); } return pagination; }
private IndexSizePagination setUpPagination(@QueryParam(IndexSizePagination.INDEX_PARAM) Optional<IntegerParam> pageIndex, @QueryParam(IndexSizePagination.SIZE_PARAM) Optional<IntegerParam> pageSize) { IndexSizePagination pagination = new IndexSizePagination(pageIndex.map(IntParam::get), pageSize.map(IntParam::get), register.getTotalRecords()); if (pagination.hasNextPage()) { httpServletResponseAdapter.addLinkHeader("next", pagination.getNextPageLink()); } if (pagination.hasPreviousPage()) { httpServletResponseAdapter.addLinkHeader("previous", pagination.getPreviousPageLink()); } return pagination; }
@GET @Path("/entries") @Produces(ExtraMediaType.TEXT_HTML) @Timed public PaginatedView<EntryListView> entriesHtml(@QueryParam("start") Optional<IntegerParam> optionalStart, @QueryParam("limit") Optional<IntegerParam> optionalLimit) { int totalEntries = register.getTotalEntries(); StartLimitPagination startLimitPagination = new StartLimitPagination(optionalStart.map(IntParam::get), optionalLimit.map(IntParam::get), totalEntries); Collection<Entry> entries = register.getEntries(startLimitPagination.start, startLimitPagination.limit); setHeaders(startLimitPagination); return viewFactory.getEntriesView(entries, startLimitPagination); }
@GET @Path("{channel}") @RequiresPermissions("system|replicate_databus") @Timed(name = "bv.emodb.databus.ReplicationResource1.get", absolute = true) public List<ReplicationEvent> get(@PathParam("channel") String channel, @QueryParam("limit") @DefaultValue("100") IntParam limit) { return _replicationSource.get(channel, limit.get()); }
@GET @Path("{subscription}/peek") public List<Event> peek(@PathParam("subscription") String subscription, @QueryParam("limit") @DefaultValue("10") IntParam limit) { checkLegalSubscriptionName(subscription); return fromInternal(_eventStore.peek(subscription, limit.get())); }
@GET @Path("{subscription}/poll") public List<Event> poll(@PathParam("subscription") String subscription, @QueryParam("ttl") @DefaultValue("30") SecondsParam claimTtl, @QueryParam("limit") @DefaultValue("10") IntParam limit) { checkLegalSubscriptionName(subscription); return fromInternal(_eventStore.poll(subscription, claimTtl.get(), limit.get())); }
@GET @Path("{queue}/peek") @RequiresPermissions("queue|poll|{queue}") @Timed(name = "bv.emodb.queue.QueueResource1.peek", absolute = true) @ApiOperation (value = "Peek operation.", notes = "Returns a List of Messages", response = Message.class ) public List<Message> peek(@PathParam("queue") String queue, @QueryParam("limit") @DefaultValue("10") IntParam limit) { // Not partitioned. Peeking ignores claims. return _queueService.peek(queue, limit.get()); }
@GET @Path("{queue}/poll") @RequiresPermissions("queue|poll|{queue}") @Timed(name = "bv.emodb.queue.QueueResource1.poll", absolute = true) @ApiOperation (value = "Poll operation", notes = "Returns a List of Messages.", response = Message.class ) public List<Message> poll(@QueryParam("partitioned") BooleanParam partitioned, @PathParam("queue") String queue, @QueryParam("ttl") @DefaultValue("30") SecondsParam claimTtl, @QueryParam("limit") @DefaultValue("10") IntParam limit, @Authenticated Subject subject) { return getService(partitioned, subject.getAuthenticationId()).poll(queue, claimTtl.get(), limit.get()); }
@GET @Path("{queue}/peek") @RequiresPermissions("queue|poll|{queue}") @Timed(name = "bv.emodb.dedupq.DedupQueueResource1.peek", absolute = true) @ApiOperation (value = "Peek operation.", notes = "Returns a List of Messages.", response = Message.class ) public List<Message> peek(@QueryParam("partitioned") BooleanParam partitioned, @PathParam("queue") String queue, @QueryParam("limit") @DefaultValue("10") IntParam limit, @Authenticated Subject subject) { // Not partitioned. Peeking ignores claims. return getService(partitioned, subject.getAuthenticationId()).peek(queue, limit.get()); }
@GET @Path("{queue}/poll") @RequiresPermissions("queue|poll|{queue}") @Timed(name = "bv.emodb.dedupq.DedupQueueResource1.poll", absolute = true) @ApiOperation (value = "Poll operation.", notes = "Returns a List of Messages", response = Message.class ) public List<Message> poll(@QueryParam("partitioned") BooleanParam partitioned, @PathParam("queue") String queue, @QueryParam("ttl") @DefaultValue("30") SecondsParam claimTtl, @QueryParam("limit") @DefaultValue("10") IntParam limit, @Authenticated Subject subject) { return getService(partitioned, subject.getAuthenticationId()).poll(queue, claimTtl.get(), limit.get()); }
@GET @Path ("_table/{table}/size") @RequiresPermissions ("sor|read|{table}") @Timed (name = "bv.emodb.sor.DataStoreResource1.getTableSize", absolute = true) @ApiOperation (value = "Returns Table Size", notes = "Returns a long", response = long.class ) public long getTableSize(@PathParam ("table") String table, @QueryParam ("limit") @Nullable IntParam limit) { return limit == null ? _dataStore.getTableApproximateSize(table) : _dataStore.getTableApproximateSize(table, limit.get()); }
/** * Retrieves a list split identifiers for the specified table. */ @GET @Path ("_split/{table}") @RequiresPermissions ("sor|read|{table}") @Timed (name = "bv.emodb.sor.DataStoreResource1.getSplits", absolute = true) @ApiOperation (value = "Retrieves a list split identifiers for the specified table.", notes = "Retrieves a list split identifiers for the specified table.", response = Collection.class ) public Collection<String> getSplits(@PathParam ("table") String table, @QueryParam ("size") @DefaultValue ("10000") IntParam desiredRecordsPerSplit) { return _dataStore.getSplits(table, desiredRecordsPerSplit.get()); }
@GET @Path("/{keyspace}/{slices}") public List<Token> describe( @PathParam("keyspace") NonEmptyStringParam keyspace, @PathParam("slices") IntParam slices ) throws Exception { String ks = retrieveKeyspace(keyspace); String partitioner = config.defaultNode().getPartitioner(); Ring ring = new Ring(partitioner, slices.get()); List<String> ranges = config.defaultNode().describeRing(ks); return ring.getTokensFromRanges(ranges); }
@GET @Timed @UnitOfWork @Path("/list/{id}") public List<Temperatureentry> findTemperatureEntry(@PathParam("id") IntParam id) { return temperatureDao.findAll(id.get()); }
@GET @Timed @UnitOfWork @Path("/{id}") public LogSession findSessionId(@PathParam("id") IntParam id) { return sessionDao.findById(id.get()); }
@GET @Path("/neighbors/{id}") @ApiOperation(value = "Get neighbors", response = Graph.class) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) @Produces({MediaType.APPLICATION_JSON, CustomMediaTypes.APPLICATION_GRAPHSON, MediaType.APPLICATION_XML, CustomMediaTypes.APPLICATION_GRAPHML, CustomMediaTypes.APPLICATION_XGMML, CustomMediaTypes.TEXT_GML, CustomMediaTypes.TEXT_CSV, CustomMediaTypes.TEXT_TSV, CustomMediaTypes.IMAGE_JPEG, CustomMediaTypes.IMAGE_PNG}) public Object getNeighbors( @ApiParam(value = DocumentationStrings.GRAPH_ID_DOC, required = true) @PathParam("id") String id, @ApiParam(value = "How far to traverse neighbors", required = false) @QueryParam("depth") @DefaultValue("1") IntParam depth, @ApiParam(value = "Traverse blank nodes", required = false) @QueryParam("blankNodes") @DefaultValue("false") BooleanParam traverseBlankNodes, @ApiParam(value = "Which relationship to traverse", required = false) @QueryParam("relationshipType") Optional<String> relationshipType, @ApiParam(value = DocumentationStrings.DIRECTION_DOC, required = false, allowableValues = DocumentationStrings.DIRECTION_ALLOWED) @QueryParam("direction") @DefaultValue("BOTH") String direction, @ApiParam(value = "Should subproperties and equivalent properties be included", required = false) @QueryParam("entail") @DefaultValue("false") BooleanParam entail, @ApiParam(value = DocumentationStrings.PROJECTION_DOC, required = false) @QueryParam("project") @DefaultValue("*") Set<String> projection, @ApiParam(value = DocumentationStrings.JSONP_DOC, required = false) @QueryParam("callback") String callback) { return getNeighborsFromMultipleRoots(newHashSet(id), depth, traverseBlankNodes, relationshipType, direction, entail, projection, callback); }
@POST @Path("/entities") @Consumes("application/x-www-form-urlencoded") @ApiOperation(value = "Get entities from text", response = EntityAnnotation.class, responseContainer = "List", notes = "Get the entities from content without embedding them in the source - only the entities are returned. " + DocumentationStrings.REST_ABUSE_DOC) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Object postEntities( @ApiParam( value = DocumentationStrings.CONTENT_DOC, required = true) final @FormParam("content") @DefaultValue("") String content, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @FormParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @FormParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @FormParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @FormParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @FormParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @FormParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @FormParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers) { return getEntities(content, includeCategories, excludeCategories, minLength, longestOnly, includeAbbrev, includeAcronym, includeNumbers); }
/*** * A convenience call for retrieving both a list of entities and annotated content * * @param content The content to annotate * @param includeCategories A set of categories to include * @param excludeCategories A set of categories to exclude * @param minLength The minimum length of annotated entities * @param longestOnly Should only the longest entity be returned for an overlapping group * @param includeAbbrev Should abbreviations be included * @param includeAcronym Should acronyms be included * @param includeNumbers Should numbers be included * @return A list of entities and the annotated content * @throws IOException */ @POST @Path("/complete") @Consumes("application/x-www-form-urlencoded") @ApiOperation(value = "Get embedded annotations as well as a separate list", response = Annotations.class, notes="A convenience resource for retrieving both a list of entities and annotated content. " + DocumentationStrings.REST_ABUSE_DOC) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Annotations postEntitiesAndContent( @ApiParam( value = DocumentationStrings.CONTENT_DOC, required = true) final @FormParam("content") @DefaultValue("") String content, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @FormParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @FormParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @FormParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @FormParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @FormParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @FormParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @FormParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers) throws IOException { return this.getEntitiesAndContent(content, includeCategories, excludeCategories, minLength, longestOnly, includeAbbrev, includeAcronym, includeNumbers); }
@POST @Timed public Response put(@QueryParam("summary") @DefaultValue("false") BooleanFlag summary, @QueryParam("details") @DefaultValue("false") BooleanFlag details, @QueryParam("sync") @DefaultValue("false") BooleanFlag sync, @QueryParam("sync_timeout") @DefaultValue("120000") IntParam sync_timeout, JsonNode body) throws Exception { LOG.trace("put; summary: {}, details: {}, sync: {}, sync_timeout: {}, body: {}", summary, details, sync, sync_timeout, body); WriteBatch batch = ts.writeBatch(); try { batch.setFlushMode(SessionConfiguration.FlushMode.AUTO_FLUSH_BACKGROUND); if (sync_timeout.get() > 0) batch.setTimeoutMillis(sync_timeout.get()); int datapoints = 0; List<Error> errors = new ArrayList<>(); Iterator<JsonNode> nodes; if (body.isArray()) { nodes = body.elements(); } else { nodes = Iterators.singletonIterator(body); } while (nodes.hasNext()) { datapoints++; JsonNode node = nodes.next(); try { Datapoint datapoint = mapper.treeToValue(node, Datapoint.class); batch.writeDatapoint(datapoint.getMetric(), datapoint.getTags(), datapoint.getTimestamp(), datapoint.getValue()); } catch (JsonProcessingException e) { errors.add(new Error(node, e.getMessage())); } } batch.flush(); RowErrorsAndOverflowStatus batchErrors = batch.getPendingErrors(); for (RowError rowError : batchErrors.getRowErrors()) { errors.add(new Error(null, rowError.getErrorStatus().toString() + " (op " + rowError.getOperation().toString() + ")")); } if (errors.isEmpty()) { LOG.debug("put {} datapoints: {}", datapoints, body); return Response.noContent().build(); } else { LOG.error("failed to write {} of {} body: {}", errors.size(), datapoints, errors); if (details.get()) { Detail detail = new Detail(errors, errors.size(), datapoints - errors.size()); return Response.status(Response.Status.BAD_REQUEST).entity(detail).build(); } else if (summary.get()) { Summary s = new Summary(errors.size(), datapoints - errors.size()); return Response.status(Response.Status.BAD_REQUEST).entity(s).build(); } else { return Response.status(Response.Status.BAD_REQUEST).build(); } } } finally { batch.close(); } }
@GET @Path("/autocomplete/{term}") @ApiOperation(value = "Find a concept by its prefix", notes = "This resource is designed for autocomplete services.", response = Completion.class, responseContainer = "List") @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public List<Completion> findByPrefix( @ApiParam( value = "Term prefix to find", required = true ) @PathParam("term") String termPrefix, @ApiParam( value = DocumentationStrings.RESULT_LIMIT_DOC, required = false ) @QueryParam("limit") @DefaultValue("20") IntParam limit, @ApiParam( value = DocumentationStrings.SEARCH_SYNONYMS, required = false ) @QueryParam("searchSynonyms") @DefaultValue("true") BooleanParam searchSynonyms, @ApiParam( value = DocumentationStrings.SEARCH_ABBREVIATIONS, required = false ) @QueryParam("searchAbbreviations") @DefaultValue("false") BooleanParam searchAbbreviations, @ApiParam( value = DocumentationStrings.SEARCH_ACRONYMS, required = false ) @QueryParam("searchAcronyms") @DefaultValue("false") BooleanParam searchAcronyms, @ApiParam( value = DocumentationStrings.INCLUDE_DEPRECATED_CLASSES, required = false ) @QueryParam("includeDeprecated") @DefaultValue("false") BooleanParam includeDeprecated, @ApiParam( value = "Categories to search (defaults to all)", required = false ) @QueryParam("category") List<String> categories, @ApiParam( value = "CURIE prefixes to search (defaults to all)", required = false ) @QueryParam("prefix") List<String> prefixes) { Vocabulary.Query.Builder builder = new Vocabulary.Query.Builder(termPrefix). categories(categories). prefixes(prefixes). includeDeprecated(includeDeprecated.get()). includeSynonyms(searchSynonyms.get()). includeAbbreviations(searchAbbreviations.get()). includeAcronyms(searchAcronyms.get()). limit(1000); List<Concept> concepts = vocabulary.getConceptsFromPrefix(builder.build()); List<Completion> completions = getCompletions(builder.build(), concepts); // TODO: Move completions to scigraph-core for #51 sort(completions); int endIndex = limit.get() > completions.size() ? completions.size() : limit.get(); completions = completions.subList(0, endIndex); return completions; }
@GET @Path("/term/{term}") @ApiOperation(value = "Find a concept from a term", notes = "Makes a best effort to provide \"exactish\" matching. " + "Individual tokens within multi-token labels are not matched" + " (ie: \"foo bar\" would not be returned by a search for \"bar\")." + " Results are not guaranteed to be unique.", response = Concept.class, responseContainer="List") @ApiResponses({ @ApiResponse(code = 404, message = "Concept with term could not be found") }) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public List<ConceptDTO> findByTerm( @ApiParam( value = "Term to find", required = true ) @PathParam("term") String term, @ApiParam( value = DocumentationStrings.RESULT_LIMIT_DOC, required = false ) @QueryParam("limit") @DefaultValue("20") IntParam limit, @ApiParam( value = DocumentationStrings.SEARCH_SYNONYMS, required = false ) @QueryParam("searchSynonyms") @DefaultValue("true") BooleanParam searchSynonyms, @ApiParam( value = DocumentationStrings.SEARCH_ABBREVIATIONS, required = false ) @QueryParam("searchAbbreviations") @DefaultValue("false") BooleanParam searchAbbreviations, @ApiParam( value = DocumentationStrings.SEARCH_ACRONYMS, required = false ) @QueryParam("searchAcronyms") @DefaultValue("false") BooleanParam searchAcronyms, @ApiParam( value = "Categories to search (defaults to all)", required = false ) @QueryParam("category") List<String> categories, @ApiParam( value = "CURIE prefixes to search (defaults to all)", required = false ) @QueryParam("prefix") List<String> prefixes) { Vocabulary.Query.Builder builder = new Vocabulary.Query.Builder(term). categories(categories). prefixes(prefixes). includeSynonyms(searchSynonyms.get()). includeAbbreviations(searchAbbreviations.get()). includeAcronyms(searchAcronyms.get()). limit(limit.get()); List<Concept> concepts = vocabulary.getConceptsFromTerm(builder.build()); if (concepts.isEmpty()) { throw new WebApplicationException(404); } else { List<ConceptDTO> dtos = transform(concepts, conceptDtoTransformer); return dtos; } }
@GET @Path("/search/{term}") @ApiOperation(value = "Find a concept from a term fragment", notes = "Searches the complete text of the term. " + "Individual tokens within multi-token labels are matched" + " (ie: \"foo bar\" would be returned by a search for \"bar\"). Results are not guaranteed to be unique.", response = ConceptDTO.class, responseContainer= "List") @ApiResponses({ @ApiResponse(code = 404, message = "Concept with term could not be found") }) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public List<ConceptDTO> searchByTerm( @ApiParam( value = "Term to find", required = true ) @PathParam("term") String term, @ApiParam( value = DocumentationStrings.RESULT_LIMIT_DOC, required = false ) @QueryParam("limit") @DefaultValue("20") IntParam limit, @ApiParam( value = DocumentationStrings.SEARCH_SYNONYMS, required = false ) @QueryParam("searchSynonyms") @DefaultValue("true") BooleanParam searchSynonyms, @ApiParam( value = DocumentationStrings.SEARCH_ABBREVIATIONS, required = false ) @QueryParam("searchAbbreviations") @DefaultValue("false") BooleanParam searchAbbreviations, @ApiParam( value = DocumentationStrings.SEARCH_ACRONYMS, required = false ) @QueryParam("searchAcronyms") @DefaultValue("false") BooleanParam searchAcronyms, @ApiParam( value = "Categories to search (defaults to all)", required = false ) @QueryParam("category") List<String> categories, @ApiParam( value = "CURIE prefixes to search (defaults to all)", required = false ) @QueryParam("prefix") List<String> prefixes) { Vocabulary.Query.Builder builder = new Vocabulary.Query.Builder(term). categories(categories). prefixes(prefixes). includeSynonyms(searchSynonyms.get()). includeAbbreviations(searchAbbreviations.get()). includeAcronyms(searchAcronyms.get()). limit(limit.get()); List<Concept> concepts = vocabulary.searchConcepts(builder.build()); if (concepts.isEmpty()) { throw new WebApplicationException(404); } else { List<ConceptDTO> dtos = transform(concepts, conceptDtoTransformer); return dtos; } }
@GET @Produces("text/plain; charset=utf-8") @ApiOperation(value = "Annotate text", response = String.class, notes="This service is designed to annotate shorter fragments of text. Use the POST version if your content is too long.") @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Response annotate( @ApiParam( value = DocumentationStrings.CONTENT_DOC, required = true) final @QueryParam("content") @DefaultValue("") String content, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @QueryParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @QueryParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @QueryParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @QueryParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @QueryParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers) { StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { Writer writer = new BufferedWriter(new OutputStreamWriter(os)); EntityFormatConfiguration.Builder configBuilder = new EntityFormatConfiguration.Builder(new StringReader(content)).writeTo(writer); configBuilder.includeCategories(includeCategories); configBuilder.excludeCategories(excludeCategories); configBuilder.longestOnly(longestOnly.get()); configBuilder.includeAbbreviations(includeAbbrev.get()); configBuilder.includeAncronyms(includeAcronym.get()); configBuilder.includeNumbers(includeNumbers.get()); configBuilder.minLength(minLength.get()); try { processor.annotateEntities(configBuilder.get()); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } writer.flush(); } }; return Response.ok(stream).build(); }
@GET @Path("/url") @Produces(MediaType.TEXT_HTML) @ApiOperation(value = "Annotate a URL", response = String.class, notes="Annotate the content of a URL (presumably an HTML page). <em>NOTE:</em> this method will add a <base> element to the head.") @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Response annotateUrl( @ApiParam( value = "", required = true) final @QueryParam("url") @DefaultValue("") String url, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @QueryParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @QueryParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @QueryParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @QueryParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @QueryParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers, @ApiParam( value = DocumentationStrings.IGNORE_TAGS_DOC, required = false) final @QueryParam("ignoreTag") Set<String> ignoreTags, @ApiParam( value = DocumentationStrings.STYLESHEETS_DOC, required = false) final @QueryParam("stylesheet") List<String> stylesheets, @ApiParam( value = DocumentationStrings.SCRIPTS_DOC, required = false) final @QueryParam("scripts") List<String> scripts, @ApiParam( value = DocumentationStrings.TARGET_IDS_DOC, required = false) final @QueryParam("targetId") Set<String> targetIds, @ApiParam( value = DocumentationStrings.CSS_CLASS_DOCS, required = false) final @QueryParam("targetClass") Set<String> targetClasses) { StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { Writer writer = new BufferedWriter(new OutputStreamWriter(os, Charsets.UTF_8)); URL source = new URL(url); try (Reader reader = new BufferedReader(new InputStreamReader(source.openStream(), Charsets.UTF_8))) { EntityFormatConfiguration.Builder configBuilder = new EntityFormatConfiguration.Builder(reader).writeTo(writer); configBuilder.includeCategories(includeCategories); configBuilder.excludeCategories(excludeCategories); configBuilder.longestOnly(longestOnly.get()); configBuilder.includeAbbreviations(includeAbbrev.get()); configBuilder.includeAncronyms(includeAcronym.get()); configBuilder.includeNumbers(includeNumbers.get()); configBuilder.minLength(minLength.get()); if (!ignoreTags.isEmpty()) { configBuilder.ignoreTags(ignoreTags); } configBuilder.stylesheets(stylesheets); configBuilder.scripts(scripts); configBuilder.url(source); configBuilder.targetIds(targetIds); configBuilder.targetClasses(targetClasses); try { processor.annotateEntities(configBuilder.get()); reader.close(); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } writer.flush(); } } }; return Response.ok(stream).build(); }
@POST @Consumes("application/x-www-form-urlencoded") @ApiOperation(value = "Annotate text", response = String.class, notes = "A POST resource for API clients wishing to annotate longer content. This is most likely the method of choice for most clients. " + DocumentationStrings.REST_ABUSE_DOC ) @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Response annotatePost( @ApiParam(value = DocumentationStrings.CONTENT_DOC, required = true) final @FormParam("content") @DefaultValue("") String content, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @FormParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @FormParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @FormParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @FormParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @FormParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @FormParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @FormParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers, @ApiParam( value = DocumentationStrings.IGNORE_TAGS_DOC, required = false) final @FormParam("ignoreTag") Set<String> ignoreTags, @ApiParam( value = DocumentationStrings.STYLESHEETS_DOC, required = false) final @FormParam("stylesheet") List<String> stylesheets, @ApiParam( value = DocumentationStrings.SCRIPTS_DOC, required = false) final @FormParam("scripts") List<String> scripts, @ApiParam( value = DocumentationStrings.TARGET_IDS_DOC, required = false) final @FormParam("targetId") Set<String> targetIds, @ApiParam( value = DocumentationStrings.CSS_CLASS_DOCS, required = false) final @FormParam("targetClass") Set<String> targetClasses) { StreamingOutput stream = new StreamingOutput() { @Override public void write(OutputStream os) throws IOException, WebApplicationException { Writer writer = new BufferedWriter(new OutputStreamWriter(os, Charsets.UTF_8)); EntityFormatConfiguration.Builder configBuilder = new EntityFormatConfiguration.Builder(new StringReader(content)).writeTo(writer); configBuilder.includeCategories(includeCategories); configBuilder.excludeCategories(excludeCategories); configBuilder.longestOnly(longestOnly.get()); configBuilder.includeAbbreviations(includeAbbrev.get()); configBuilder.includeAncronyms(includeAcronym.get()); configBuilder.includeNumbers(includeNumbers.get()); configBuilder.minLength(minLength.get()); if (!ignoreTags.isEmpty()) { configBuilder.ignoreTags(ignoreTags); } configBuilder.stylesheets(stylesheets); configBuilder.scripts(scripts); configBuilder.targetIds(targetIds); configBuilder.targetClasses(targetClasses); try { processor.annotateEntities(configBuilder.get()); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } writer.flush(); } }; return Response.ok(stream).build(); }
@GET @Path("/entities") @ApiOperation(value = "Get entities from text", response = EntityAnnotation.class, responseContainer = "List", notes="Get entities from content without embedding them in the source.") @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public List<EntityAnnotation> getEntities( @ApiParam( value = DocumentationStrings.CONTENT_DOC, required = true) final @QueryParam("content") @DefaultValue("") String content, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @QueryParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @QueryParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @QueryParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @QueryParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @QueryParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers) { List<EntityAnnotation> entities = newArrayList(); try { EntityFormatConfiguration.Builder configBuilder = new EntityFormatConfiguration.Builder(new StringReader(content)); configBuilder.includeCategories(includeCategories); configBuilder.excludeCategories(excludeCategories); configBuilder.includeAbbreviations(includeAbbrev.get()); configBuilder.includeAncronyms(includeAcronym.get()); configBuilder.includeNumbers(includeNumbers.get()); configBuilder.minLength(minLength.get()); configBuilder.longestOnly(longestOnly.get()); entities = processor.annotateEntities(configBuilder.get()); } catch (Exception e) { logger.log(Level.WARNING, e.getMessage(), e); throw new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR); } return entities; }
/*** * @return A list of entities and the annotated content */ @GET @Path("/complete") @Consumes("application/x-www-form-urlencoded") @ApiOperation(value = "Get embedded annotations as well as a separate list", response = Annotations.class, notes="A convenience resource for retrieving both a list of entities and annotated content") @Timed @CacheControl(maxAge = 2, maxAgeUnit = TimeUnit.HOURS) public Annotations getEntitiesAndContent( @ApiParam( value = DocumentationStrings.CONTENT_DOC, required = true) final @QueryParam("content") @DefaultValue("") String content, @ApiParam( value = DocumentationStrings.INCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("includeCat") Set<String> includeCategories, @ApiParam( value = DocumentationStrings.EXCLUDE_CATEGORIES_DOC, required = false) final @QueryParam("excludeCat") Set<String> excludeCategories, @ApiParam( value = DocumentationStrings.MINIMUM_LENGTH_DOC, required = false) final @QueryParam("minLength") @DefaultValue("4") IntParam minLength, @ApiParam( value = DocumentationStrings.LONGEST_ENTITY_DOC, required = false) final @QueryParam("longestOnly") @DefaultValue("false") BooleanParam longestOnly, @ApiParam( value = DocumentationStrings.INCLUDE_ABBREV_DOC, required = false) final @QueryParam("includeAbbrev") @DefaultValue("false") BooleanParam includeAbbrev, @ApiParam( value = DocumentationStrings.INCLUDE_ACRONYMS_DOC, required = false) final @QueryParam("includeAcronym") @DefaultValue("false") BooleanParam includeAcronym, @ApiParam( value = DocumentationStrings.INCLUDE_NUMBERS_DOC, required = false) final @QueryParam("includeNumbers") @DefaultValue("false") BooleanParam includeNumbers ) throws IOException { Annotations annotations = new Annotations(); StringWriter writer = new StringWriter(); EntityFormatConfiguration.Builder configBuilder = new EntityFormatConfiguration.Builder(new StringReader(content)); configBuilder.includeCategories(includeCategories); configBuilder.excludeCategories(excludeCategories); configBuilder.includeAbbreviations(includeAbbrev.get()); configBuilder.includeAncronyms(includeAcronym.get()); configBuilder.includeNumbers(includeNumbers.get()); configBuilder.minLength(minLength.get()); configBuilder.longestOnly(longestOnly.get()); configBuilder.writeTo(writer); annotations.delegate = processor.annotateEntities(configBuilder.get()); annotations.content = writer.toString(); return annotations; }