当前位置: 首页>>代码示例>>Java>>正文


Java HttpRequest类代码示例

本文整理汇总了Java中com.linecorp.armeria.common.HttpRequest的典型用法代码示例。如果您正苦于以下问题:Java HttpRequest类的具体用法?Java HttpRequest怎么用?Java HttpRequest使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


HttpRequest类属于com.linecorp.armeria.common包,在下文中一共展示了HttpRequest类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: serve

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Override
public HttpResponse serve(Service<HttpRequest, HttpResponse> delegate,
                          ServiceRequestContext ctx,
                          HttpRequest req) throws Exception {
    final String projectName = ctx.pathParam("projectName");
    checkArgument(!isNullOrEmpty(projectName),
                  "No project name is specified");

    final Function<String, ProjectRole> map = ctx.attr(RoleResolvingDecorator.ROLE_MAP).get();
    final ProjectRole projectRole = map != null ? map.apply(projectName) : null;
    final User user = AuthenticationUtil.currentUser(ctx);
    if (!isAllowedRole(user, projectRole)) {
        throw HttpStatusException.of(HttpStatus.UNAUTHORIZED);
    }

    return delegate.serve(ctx, req);
}
 
开发者ID:line,项目名称:centraldogma,代码行数:18,代码来源:ProjectAccessController.java

示例2: serve

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
/**
 * Resolves all {@link ProjectRole}s of the current user and puts them into {@link RequestContext}
 * attributes.
 */
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {

    final User user = AuthenticationUtil.currentUser(ctx);

    final CompletionStage<Map<String, ProjectRole>> future;
    if (user instanceof UserWithToken) {
        future = mds.findRole(((UserWithToken) user).secret());
    } else {
        future = mds.findRoles(user);
    }

    return HttpResponse.from(future.thenApplyAsync(map -> {
        try {
            ctx.attr(ROLE_MAP).set(map::get);
            return delegate().serve(ctx, req);
        } catch (Exception e) {
            return Exceptions.throwUnsafely(e);
        }
    }, ctx.contextAwareEventLoop()));
}
 
开发者ID:line,项目名称:centraldogma,代码行数:26,代码来源:RoleResolvingDecorator.java

示例3: convertResponse

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, Object resObj) throws Exception {
    try {
        final HttpRequest request = RequestContext.current().request();
        if (HttpMethod.DELETE == request.method() ||
            (resObj instanceof Iterable && Iterables.size((Iterable) resObj) == 0)) {
            return HttpResponse.of(HttpStatus.NO_CONTENT);
        }

        final HttpData httpData = HttpData.of(Jackson.writeValueAsBytes(resObj));
        return HttpResponse.of(HttpStatus.OK, MediaType.JSON_UTF_8, httpData);
    } catch (JsonProcessingException e) {
        logger.debug("Failed to convert a response:", e);
        return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}
 
开发者ID:line,项目名称:centraldogma,代码行数:17,代码来源:HttpApiResponseConverter.java

示例4: handleException

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Override
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) {

    if (cause instanceof IllegalArgumentException) {
        if (cause.getMessage() != null) {
            return newResponseWithErrorMessage(HttpStatus.BAD_REQUEST, cause.getMessage());
        }
        return HttpResponse.of(HttpStatus.BAD_REQUEST);
    }

    if (cause instanceof StorageException) {
        // Use precomputed map if the cause is instance of StorageException to access in a faster way.
        final ExceptionHandlerFunction func = storageExceptionHandlers.get(cause.getClass());
        if (func != null) {
            return func.handleException(ctx, req, cause);
        }
    }

    return ExceptionHandlerFunction.fallthrough();
}
 
开发者ID:line,项目名称:centraldogma,代码行数:21,代码来源:HttpApiExceptionHandler.java

示例5: serve

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    final String authorization = req.headers().get(HttpHeaderNames.AUTHORIZATION);
    if (authorization == null || !PATTERN.matcher(authorization).matches()) {
        final InetSocketAddress raddr = ctx.remoteAddress();
        final String ip = raddr.getAddress().getHostAddress();
        final Instant now = Instant.now(clock);
        final Instant lastReport = reportedAddresses.putIfAbsent(ip, now);
        final boolean report;
        if (lastReport == null) {
            report = true;
        } else if (ChronoUnit.DAYS.between(lastReport, now) >= 1) {
            report = reportedAddresses.replace(ip, lastReport, now);
        } else {
            report = false;
        }

        if (report) {
            report(raddr.getHostString(), ip);
        }
    }

    return delegate().serve(ctx, req);
}
 
开发者ID:line,项目名称:centraldogma,代码行数:25,代码来源:TokenlessClientLogger.java

示例6: configureThriftService

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
private void configureThriftService(ServerBuilder sb, ProjectManager pm, CommandExecutor executor,
                                    WatchService watchService) {
    final CentralDogmaServiceImpl service =
            new CentralDogmaServiceImpl(pm, executor, watchService);

    Service<HttpRequest, HttpResponse> thriftService =
            ThriftCallService.of(service)
                             .decorate(CentralDogmaTimeoutScheduler::new)
                             .decorate(CentralDogmaExceptionTranslator::new)
                             .decorate(THttpService.newDecorator());

    if (cfg.isCsrfTokenRequiredForThrift()) {
        thriftService = thriftService.decorate(HttpAuthService.newDecorator(new CsrfTokenAuthorizer()));
    } else {
        thriftService = thriftService.decorate(TokenlessClientLogger::new);
    }

    sb.service("/cd/thrift/v1", thriftService);
}
 
开发者ID:line,项目名称:centraldogma,代码行数:20,代码来源:CentralDogma.java

示例7: testWithToken

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Test
public void testWithToken() throws Exception {
    final MockTokenlessClientLogger logger = new MockTokenlessClientLogger();

    // When a request with a CSRF token is received
    final ServiceRequestContext ctx = newContext("foo", "192.168.0.1");
    final HttpRequest req = newRequestWithToken();
    logger.serve(ctx, req);

    // hostname and IP address must not be reported.
    assertThat(logger.hostname).isNull();
    assertThat(logger.ip).isNull();
    // .. and the request must be delegated.
    verify(delegate, times(1)).serve(ctx, req);
    // .. and clock must not be queried.
    verify(clock, never()).instant();
}
 
开发者ID:line,项目名称:centraldogma,代码行数:18,代码来源:TokenlessClientLoggerTest.java

示例8: yummlyApi

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Provides
@Singleton
static YummlyApi yummlyApi(YummlyConfig config) {
  return new ArmeriaRetrofitBuilder()
      .baseUrl("http://api.yummly.com/v1/api/")
      .addCallAdapterFactory(GuavaCallAdapterFactory.create())
      .addConverterFactory(JacksonConverterFactory.create(OBJECT_MAPPER))
      .withClientOptions(
          (unused, options) ->
              options
                  .addHttpHeader(HttpHeaderNames.of("X-Yummly-App-ID"), config.getApiId())
                  .addHttpHeader(HttpHeaderNames.of("X-Yummly-App-Key"), config.getApiKey())
                  .decorator(HttpRequest.class, HttpResponse.class, LoggingClient.newDecorator()))
      .build()
      .create(YummlyApi.class);
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:17,代码来源:YummlyApiModule.java

示例9: annotatedService

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
/**
 * Binds the specified annotated service object under the specified path prefix.
 *
 * @param exceptionHandlersAndConverters an iterable object of {@link ExceptionHandlerFunction},
 *                                       {@link RequestConverterFunction} and/or
 *                                       {@link ResponseConverterFunction}
 */
public B annotatedService(String pathPrefix, Object service,
                          Function<Service<HttpRequest, HttpResponse>,
                                  ? extends Service<HttpRequest, HttpResponse>> decorator,
                          Iterable<?> exceptionHandlersAndConverters) {

    requireNonNull(pathPrefix, "pathPrefix");
    requireNonNull(service, "service");
    requireNonNull(decorator, "decorator");
    requireNonNull(exceptionHandlersAndConverters, "exceptionHandlersAndConverters");

    final List<AnnotatedHttpService> entries =
            AnnotatedHttpServices.build(pathPrefix, service, exceptionHandlersAndConverters);
    entries.forEach(e -> service(e.pathMapping(), decorator.apply(e.decorator().apply(e))));
    return self();
}
 
开发者ID:line,项目名称:armeria,代码行数:23,代码来源:AbstractVirtualHostBuilder.java

示例10: testFaultyDelegate

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
/**
 * Tests the case where a delegate raises an exception rather than returning a response.
 */
@Test
public void testFaultyDelegate() throws Exception {
    final ClientRequestContext ctx = newContext();
    final HttpRequest req = mock(HttpRequest.class);

    @SuppressWarnings("unchecked")
    final Client<HttpRequest, HttpResponse> delegate = mock(Client.class);
    when(delegate.execute(ctx, req)).thenThrow(Exception.class);

    final ConcurrencyLimitingHttpClient client =
            ConcurrencyLimitingHttpClient.newDecorator(1).apply(delegate);
    assertThat(client.numActiveRequests()).isZero();

    final HttpResponse res = client.execute(ctx, req);

    // Consume everything from the returned response so its close future is completed.
    res.subscribe(NoopSubscriber.get());

    assertThat(res.isOpen()).isFalse();
    assertThatThrownBy(() -> res.completionFuture().get()).hasCauseInstanceOf(Exception.class);
    await().untilAsserted(() -> assertThat(client.numActiveRequests()).isZero());
}
 
开发者ID:line,项目名称:armeria,代码行数:26,代码来源:ConcurrencyLimitingHttpClientTest.java

示例11: build

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
/**
 * Constructs a new {@link GrpcService} that can be bound to
 * {@link com.linecorp.armeria.server.ServerBuilder}. It is recommended to bind the service to a server
 * using {@link com.linecorp.armeria.server.ServerBuilder#service(ServiceWithPathMappings)} to mount all
 * service paths without interfering with other services.
 */
public ServiceWithPathMappings<HttpRequest, HttpResponse> build() {
    HandlerRegistry handlerRegistry = registryBuilder.build();
    GrpcService grpcService = new GrpcService(
            handlerRegistry,
            handlerRegistry
                  .methods()
                  .keySet()
                  .stream()
                  .map(path -> PathMapping.ofExact("/" + path))
                  .collect(ImmutableSet.toImmutableSet()),
            firstNonNull(decompressorRegistry, DecompressorRegistry.getDefaultInstance()),
            firstNonNull(compressorRegistry, CompressorRegistry.getDefaultInstance()),
            supportedSerializationFormats, maxOutboundMessageSizeBytes,
            maxInboundMessageSizeBytes);
    return enableUnframedRequests ? grpcService.decorate(UnframedGrpcService::new) : grpcService;
}
 
开发者ID:line,项目名称:armeria,代码行数:23,代码来源:GrpcServiceBuilder.java

示例12: missingMethod

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Test
public void missingMethod() throws Exception {
    when(ctx.mappedPath()).thenReturn("/grpc.testing.TestService/FooCall");
    HttpResponse response = grpcService.doPost(
            ctx,
            HttpRequest.of(HttpHeaders.of(HttpMethod.POST, "/grpc.testing.TestService/FooCall")
                                      .set(HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto")));
    assertThat(response.aggregate().get()).isEqualTo(AggregatedHttpMessage.of(
            HttpHeaders.of(HttpStatus.OK)
                       .set(HttpHeaderNames.CONTENT_TYPE, "application/grpc+proto")
                       .set(AsciiString.of("grpc-status"), "12")
                       .set(AsciiString.of("grpc-message"),
                            "Method not found: grpc.testing.TestService/FooCall")
                       .set(HttpHeaderNames.CONTENT_LENGTH, "0"),
            HttpData.of(new byte[] {})));
}
 
开发者ID:line,项目名称:armeria,代码行数:17,代码来源:GrpcServiceTest.java

示例13: serve

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Override
public HttpResponse serve(ServiceRequestContext ctx, HttpRequest req) throws Exception {
    HttpResponse res = delegate().serve(ctx, req);
    return new FilteredHttpResponse(res) {
        private boolean headersReceived;

        @Override
        protected HttpObject filter(HttpObject obj) {
            if (obj instanceof HttpHeaders) {
                if (!headersReceived) {
                    headersReceived = true;
                } else {
                    HttpHeaders trailers = (HttpHeaders) obj;
                    String extraHeader = req.headers().get(EXTRA_HEADER_NAME);
                    if (extraHeader != null) {
                        trailers.set(EXTRA_HEADER_NAME, extraHeader);
                    }
                }
            }
            return obj;
        }
    };
}
 
开发者ID:line,项目名称:armeria,代码行数:24,代码来源:TestServiceImpl.java

示例14: makeRequest

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
private static void makeRequest(String name) throws Exception {
    TestServiceBlockingStub client = new ClientBuilder(server.uri(GrpcSerializationFormats.PROTO, "/"))
            .factory(clientFactory)
            .decorator(HttpRequest.class, HttpResponse.class,
                       MetricCollectingClient.newDecorator(
                               MeterIdPrefixFunction.ofDefault("client")))
            .build(TestServiceBlockingStub.class);

    SimpleRequest request =
            SimpleRequest.newBuilder()
                         .setPayload(Payload.newBuilder()
                                            .setBody(ByteString.copyFromUtf8(name)))
                         .build();
    try {
        client.unaryCall(request);
    } catch (Throwable t) {
        // Ignore, we will count these up
    }
}
 
开发者ID:line,项目名称:armeria,代码行数:20,代码来源:GrpcMetricsIntegrationTest.java

示例15: determineSerializationFormat

import com.linecorp.armeria.common.HttpRequest; //导入依赖的package包/类
@Nullable
private SerializationFormat determineSerializationFormat(HttpRequest req) {
    final HttpHeaders headers = req.headers();
    final MediaType contentType = headers.contentType();

    SerializationFormat serializationFormat;
    if (contentType != null) {
        serializationFormat = findSerializationFormat(contentType);
        if (serializationFormat == null) {
            return null;
        }
    } else {
        serializationFormat = defaultSerializationFormat();
    }
    return serializationFormat;
}
 
开发者ID:line,项目名称:armeria,代码行数:17,代码来源:THttpService.java


注:本文中的com.linecorp.armeria.common.HttpRequest类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。