com.linecorp.armeria.server.annotation.Get Java Examples

The following examples show how to use com.linecorp.armeria.server.annotation.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: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 6 votes vote down vote up
@Get("/serviceNames")
@ProducesJson
public JsonNode getServiceNames() {
  try {
    if (!storage.traceSearchEnabled) return MAPPER.createArrayNode();
    ReadOnlyKeyValueStore<String, String> store = storage.getTraceStorageStream()
        .store(SERVICE_NAMES_STORE_NAME, QueryableStoreTypes.keyValueStore());
    ArrayNode array = MAPPER.createArrayNode();
    try (KeyValueIterator<String, String> all = store.all()) {
      all.forEachRemaining(keyValue -> array.add(keyValue.value));
    }
    return array;
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    throw e;
  }
}
 
Example #2
Source File: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 6 votes vote down vote up
@Get("/serviceNames/:service_name/spanNames")
@ProducesJson
public JsonNode getSpanNames(@Param("service_name") String serviceName) {
  try {
    if (!storage.traceSearchEnabled) return MAPPER.createArrayNode();
    ReadOnlyKeyValueStore<String, Set<String>> store = storage.getTraceStorageStream()
        .store(SPAN_NAMES_STORE_NAME, QueryableStoreTypes.keyValueStore());
    Set<String> names = store.get(serviceName);
    ArrayNode array = MAPPER.createArrayNode();
    if (names != null) names.forEach(array::add);
    return array;
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    throw e;
  }
}
 
Example #3
Source File: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 6 votes vote down vote up
@Get("/traceMany")
public AggregatedHttpResponse getTraces(@Param("traceIds") String traceIds) {
  try {
    if (!storage.traceByIdQueryEnabled) return AggregatedHttpResponse.of(HttpStatus.NOT_FOUND);
    ReadOnlyKeyValueStore<String, List<Span>> store = storage.getTraceStorageStream()
        .store(TRACES_STORE_NAME, QueryableStoreTypes.keyValueStore());
    List<List<Span>> result = new ArrayList<>();
    for (String traceId : traceIds.split(",", 1000)) {
      result.add(store.get(traceId));
    }
    return AggregatedHttpResponse.of(HttpStatus.OK, MediaType.JSON, writeTraces(result));
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    return AggregatedHttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE);
  }
}
 
Example #4
Source File: ArmeriaUserServiceServerImpl.java    From rpc-benchmark with Apache License 2.0 6 votes vote down vote up
@Get("/get-user")
public HttpResponse getUser(@Param("id") long id) throws JsonProcessingException {
	User user = new User();

	user.setId(id);
	user.setName("Doug Lea");
	user.setSex(1);
	user.setBirthday(LocalDate.of(1968, 12, 8));
	user.setEmail("[email protected]");
	user.setMobile("18612345678");
	user.setAddress("北京市 中关村 中关村大街1号 鼎好大厦 1605");
	user.setIcon("https://www.baidu.com/img/bd_logo1.png");
	user.setStatus(1);
	user.setCreateTime(LocalDateTime.now());
	user.setUpdateTime(user.getCreateTime());

	List<Integer> permissions = new ArrayList<>(List.of(1, 2, 3, 4, 5, 6, 7, 8, 19, 88, 86, 89, 90, 91, 92));
	user.setPermissions(permissions);

	return HttpResponse.of(objectMapper.writeValueAsString(user));
}
 
Example #5
Source File: RepositoryService.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * GET /projects/{projectName}/repositories/{repoName}/history{path}?from=x.x&amp;to=x.x
 * Returns a history between the specified revisions.
 */
@Get("regex:/projects/(?<projectName>[^/]+)/repositories/(?<repoName>[^/]+)" +
     "/history(?<path>/.*$)")
public CompletionStage<List<CommitDto>> getHistory(@Param String projectName,
                                                   @Param String repoName,
                                                   @Param String path,
                                                   @Param @Default("-1") String from,
                                                   @Param @Default("1") String to) {
    return projectManager().get(projectName).repos().get(repoName)
                           .history(new Revision(from),
                                    new Revision(to),
                                    path + "**")
                           .thenApply(commits -> commits.stream()
                                                        .map(DtoConverter::convert)
                                                        .collect(toList()));
}
 
Example #6
Source File: ContentServiceV1.java    From centraldogma with Apache License 2.0 6 votes vote down vote up
/**
 * GET /projects/{projectName}/repos/{repoName}/compare?
 * path={path}&amp;from={from}&amp;to={to}&amp;jsonpath={jsonpath} returns a diff.
 *
 * <p>or,
 *
 * <p>GET /projects/{projectName}/repos/{repoName}/compare?
 * pathPattern={pathPattern}&amp;from={from}&amp;to={to} returns diffs.
 */
@Get("/projects/{projectName}/repos/{repoName}/compare")
public CompletableFuture<?> getDiff(
        @Param @Default("/**") String pathPattern,
        @Param @Default("1") String from, @Param @Default("head") String to,
        Repository repository,
        @RequestConverter(QueryRequestConverter.class) @Nullable Query<?> query) {

    if (query != null) {
        return repository.diff(new Revision(from), new Revision(to), query)
                         .thenApply(DtoConverter::convert);
    } else {
        return repository
                .diff(new Revision(from), new Revision(to), normalizePath(pathPattern))
                .thenApply(changeMap -> changeMap.values().stream()
                                                 .map(DtoConverter::convert).collect(toImmutableList()));
    }
}
 
Example #7
Source File: AnnotatedDocServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/foo")
@Description("foo method")
public <T> T foo(@Header @Description("header parameter") int header,
                 @Param @Description("query parameter") long query) {
    @SuppressWarnings("unchecked")
    final T result = (T) ("header: " + header + ", query: " + query);
    return result;
}
 
Example #8
Source File: RepositoryService.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}/repositories/{repoName}/files/revisions/{revision}{path}
 * Returns the blob in the path.
 */
@Get("regex:/projects/(?<projectName>[^/]+)/repositories/(?<repoName>[^/]+)" +
     "/files/revisions/(?<revision>[^/]+)(?<path>/.*$)")
public CompletionStage<EntryDto> getFile(@Param String projectName,
                                         @Param String repoName,
                                         @Param String revision,
                                         @Param String path,
                                         @Param @Default("IDENTITY") QueryType queryType,
                                         @Param @Default("") String expression) {

    final Query<?> query = Query.of(queryType,path, expression);
    final Repository repo = projectManager().get(projectName).repos().get(repoName);
    return repo.get(repo.normalizeNow(new Revision(revision)), query)
               .thenApply(DtoConverter::convert);
}
 
Example #9
Source File: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 5 votes vote down vote up
@Get("/dependencies")
public AggregatedHttpResponse getDependencies(
    @Param("endTs") long endTs,
    @Param("lookback") long lookback
) {
  try {
    if (!storage.dependencyQueryEnabled) return AggregatedHttpResponse.of(HttpStatus.NOT_FOUND);
    ReadOnlyWindowStore<Long, DependencyLink> store =
        storage.getDependencyStorageStream()
            .store(DEPENDENCIES_STORE_NAME, QueryableStoreTypes.windowStore());
    List<DependencyLink> links = new ArrayList<>();
    Instant from = Instant.ofEpochMilli(endTs - lookback);
    Instant to = Instant.ofEpochMilli(endTs);
    try (KeyValueIterator<Windowed<Long>, DependencyLink> iterator = store.fetchAll(from, to)) {
      iterator.forEachRemaining(keyValue -> links.add(keyValue.value));
    }
    List<DependencyLink> mergedLinks = DependencyLinker.merge(links);
    LOG.debug("Dependencies found from={}-to={}: {}", from, to, mergedLinks.size());
    return AggregatedHttpResponse.of(
        HttpStatus.OK,
        MediaType.JSON,
        DependencyLinkBytesEncoder.JSON_V1.encodeList(mergedLinks));
  } catch (InvalidStateStoreException e) {
    LOG.debug("State store is not ready", e);
    return AggregatedHttpResponse.of(HttpStatus.SERVICE_UNAVAILABLE);
  }
}
 
Example #10
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get
@Path("/path/req/async/:var")
public static CompletableFuture<String> returnPathReqAsync(@Param int var,
                                                           HttpRequest req,
                                                           ServiceRequestContext ctx) {
    validateContextAndRequest(ctx, req);
    return CompletableFuture.completedFuture(req.path());
}
 
Example #11
Source File: AnnotatedServiceResponseConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/expect-combined2")
@AdditionalHeader(name = "method_header_1", value = "method_value_1")
@AdditionalHeader(name = "method_header_2", value = "method_value_2")
@AdditionalTrailer(name = "method_trailer_1", value = "method_value_1")
@AdditionalTrailer(name = "method_trailer_2", value = "method_value_2")
public String expectCombined2() {
    return "combined2";
}
 
Example #12
Source File: KafkaStorageHttpService.java    From zipkin-storage-kafka with Apache License 2.0 5 votes vote down vote up
@Get("/instances/:store_name")
@ProducesJson
public KafkaStreamsMetadata getInstancesByStore(@Param("store_name") String storeName) {
  Collection<StreamsMetadata> metadata =
      storage.getTraceStorageStream().allMetadataForStore(storeName);
  metadata.addAll(storage.getDependencyStorageStream().allMetadataForStore(storeName));
  return KafkaStreamsMetadata.create(metadata);
}
 
Example #13
Source File: AnnotatedDocServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("regex:/(bar|baz)")
public List<String>[] regex(@Param MyEnum myEnum) {
    final MyEnum[] values = MyEnum.values();
    @SuppressWarnings("unchecked")
    final List<String>[] genericArray = (List<String>[]) Array.newInstance(List.class, values.length);
    for (int i = 0; i < genericArray.length; i++) {
        genericArray[i] = ImmutableList.of(values[i].toString());
    }
    return genericArray;
}
 
Example #14
Source File: RepositoryService.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}/repositories/{repoName}/search/revisions/{revision}?term={term}
 * Finds the files matched by {@code term}.
 */
@Get("/projects/{projectName}/repositories/{repoName}/search/revisions/{revision}")
public CompletionStage<List<EntryDto>> search(@Param String projectName,
                                              @Param String repoName,
                                              @Param String revision,
                                              @Param String term) {
    return projectManager().get(projectName).repos().get(repoName)
                           .find(new Revision(revision), normalizeSearchTerm(term), FIND_ALL_WITH_CONTENT)
                           .thenApply(entries -> entries.values().stream()
                                                        .map(DtoConverter::convert)
                                                        .collect(toList()));
}
 
Example #15
Source File: UserService.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /users/me
 * Returns a login {@link User} if the user is authorized. Otherwise, {@code 401 Unauthorized} HTTP
 * response is sent.
 */
@Get("/users/me")
public HttpResponse usersMe() throws Exception {
    final User user = AuthUtil.currentUser();
    return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8,
                           HttpData.wrap(Jackson.writeValueAsBytes(user)));
}
 
Example #16
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/param/get")
public String paramGet(RequestContext ctx,
                       @Param("username") String username,
                       @Param("password") String password) {
    validateContext(ctx);
    return username + '/' + password;
}
 
Example #17
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/default/bean1/{userName}/{seqNum}")
public String defaultBean1ForGet(RequestBean1 bean1)
        throws JsonProcessingException {
    assertThat(bean1).isNotNull();
    bean1.validate();
    return mapper.writeValueAsString(bean1);
}
 
Example #18
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get
@Post
@Path("/getPostWithPathMapping1")
@Path("/getPostWithPathMapping2")
public String getPostWithPathMapping(RequestContext ctx) {
    return ctx.path();
}
 
Example #19
Source File: AnnotatedServiceRequestConverterTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/default/bean3/{userName}")
public String defaultBean3ForGet(RequestBean3 bean3)
        throws JsonProcessingException {
    assertThat(bean3).isNotNull();
    bean3.validate();
    return mapper.writeValueAsString(bean3);
}
 
Example #20
Source File: ProjectServiceV1.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}
 *
 * <p>Gets the {@link ProjectMetadata} of the specified {@code projectName}.
 * If a {@code checkPermissionOnly} parameter is {@code true}, it is returned whether the user has
 * permission to read the metadata of the specified {@code projectName}.
 */
@Get("/projects/{projectName}")
@RequiresRole(roles = { ProjectRole.OWNER, ProjectRole.MEMBER })
public CompletableFuture<ProjectMetadata> getProjectMetadata(
        @Param String projectName,
        @Param("checkPermissionOnly") @Default("false") boolean isCheckPermissionOnly) {
    if (isCheckPermissionOnly) {
        return CompletableFuture.completedFuture(null);
    }
    return mds.getProject(projectName);
}
 
Example #21
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get
@Path("/path/ctx/sync/:var")
public static String returnPathCtxSync(@Param int var,
                                       RequestContext ctx,
                                       Request req) {
    validateContextAndRequest(ctx, req);
    return ctx.path();
}
 
Example #22
Source File: ContentServiceV1.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}/repos/{repoName}/list{path}?revision={revision}
 *
 * <p>Returns the list of files in the path.
 */
@Get("regex:/projects/(?<projectName>[^/]+)/repos/(?<repoName>[^/]+)/list(?<path>(|/.*))$")
public CompletableFuture<List<EntryDto<?>>> listFiles(@Param String path,
                                                      @Param @Default("-1") String revision,
                                                      Repository repository) {
    final String normalizedPath = normalizePath(path);
    final Revision normalizedRev = repository.normalizeNow(new Revision(revision));
    final CompletableFuture<List<EntryDto<?>>> future = new CompletableFuture<>();
    listFiles(repository, normalizedPath, normalizedRev, false, future);
    return future;
}
 
Example #23
Source File: ContentServiceV1.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}/repos/{repoName}/contents{path}?revision={revision}&amp;
 * jsonpath={jsonpath}
 *
 * <p>Returns the entry of files in the path. This is same with
 * {@link #listFiles(String, String, Repository)} except that containing the content of the files.
 * Note that if the {@link HttpHeaderNames#IF_NONE_MATCH} in which has a revision is sent with,
 * this will await for the time specified in {@link HttpHeaderNames#PREFER}.
 * During the time if the specified revision becomes different with the latest revision, this will
 * response back right away to the client.
 * {@link HttpStatus#NOT_MODIFIED} otherwise.
 */
@Get("regex:/projects/(?<projectName>[^/]+)/repos/(?<repoName>[^/]+)/contents(?<path>(|/.*))$")
public CompletableFuture<?> getFiles(
        ServiceRequestContext ctx,
        @Param String path, @Param @Default("-1") String revision,
        Repository repository,
        @RequestConverter(WatchRequestConverter.class) @Nullable WatchRequest watchRequest,
        @RequestConverter(QueryRequestConverter.class) @Nullable Query<?> query) {
    final String normalizedPath = normalizePath(path);

    // watch repository or a file
    if (watchRequest != null) {
        final Revision lastKnownRevision = watchRequest.lastKnownRevision();
        final long timeOutMillis = watchRequest.timeoutMillis();
        if (query != null) {
            return watchFile(ctx, repository, lastKnownRevision, query, timeOutMillis);
        }

        return watchRepository(ctx, repository, lastKnownRevision, normalizedPath, timeOutMillis);
    }

    final Revision normalizedRev = repository.normalizeNow(new Revision(revision));
    if (query != null) {
        // get a file
        return repository.get(normalizedRev, query)
                         .handle(returnOrThrow((Entry<?> result) -> convert(repository, normalizedRev,
                                                                            result, true)));
    }

    // get files
    final CompletableFuture<List<EntryDto<?>>> future = new CompletableFuture<>();
    listFiles(repository, normalizedPath, normalizedRev, true, future);
    return future;
}
 
Example #24
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get
@Path("/path/req/sync/:var")
public static String returnPathReqSync(@Param int var,
                                       HttpRequest req,
                                       RequestContext ctx) {
    validateContextAndRequest(ctx, req);
    return req.path();
}
 
Example #25
Source File: ContentServiceV1.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}/repos/{repoName}/merge?
 * revision={revision}&amp;path={path}&amp;optional_path={optional_path}
 *
 * <p>Returns a merged entry of files which are specified in the query string.
 */
@Get("/projects/{projectName}/repos/{repoName}/merge")
public <T> CompletableFuture<?> mergeFiles(
        @Param @Default("-1") String revision, Repository repository,
        @RequestConverter(MergeQueryRequestConverter.class) MergeQuery<T> query) {
    return repository.mergeFiles(new Revision(revision), query).thenApply(DtoConverter::convert);
}
 
Example #26
Source File: RepositoryServiceV1.java    From centraldogma with Apache License 2.0 5 votes vote down vote up
/**
 * GET /projects/{projectName}/repos/{repoName}/revision/{revision}
 *
 * <p>Normalizes the revision into an absolute revision.
 */
@Get("/projects/{projectName}/repos/{repoName}/revision/{revision}")
@RequiresReadPermission
public Map<String, Integer> normalizeRevision(Repository repository, @Param String revision) {
    final Revision normalizedRevision = repository.normalizeNow(new Revision(revision));
    return ImmutableMap.of("revision", normalizedRevision.major());
}
 
Example #27
Source File: AnnotatedServiceFactoryTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get
@Post
@Path("/path1")
@Path("/path2")
public HttpResponse multiPathAnnotations() {
    return HttpResponse.of(HttpStatus.OK);
}
 
Example #28
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get
@Path("/path/ctx/async/:var")
public static CompletableFuture<String> returnPathCtxAsync(@Param int var,
                                                           ServiceRequestContext ctx,
                                                           Request req) {
    validateContextAndRequest(ctx, req);
    return CompletableFuture.completedFuture(ctx.path());
}
 
Example #29
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/param/enum")
public String paramEnum(RequestContext ctx,
                        @Param("username") String username,
                        @Param("level") UserLevel level) {
    validateContext(ctx);
    return username + '/' + level;
}
 
Example #30
Source File: AnnotatedServiceTest.java    From armeria with Apache License 2.0 5 votes vote down vote up
@Get("/headerWithParam")
public String headerWithParam(RequestContext ctx,
                              @Header("username") @Default("hello") String username,
                              @Header("password") @Default("world") Optional<String> password,
                              @Param("extra") Optional<String> extra,
                              @Param("number") int number) {
    validateContext(ctx);
    return username + '/' + password.get() + '/' + extra.orElse("(null)") + '/' + number;
}