本文整理汇总了Java中com.linecorp.armeria.common.HttpResponse类的典型用法代码示例。如果您正苦于以下问题:Java HttpResponse类的具体用法?Java HttpResponse怎么用?Java HttpResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
HttpResponse类属于com.linecorp.armeria.common包,在下文中一共展示了HttpResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: serve
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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);
}
示例2: serve
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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()));
}
示例3: convertResponse
import com.linecorp.armeria.common.HttpResponse; //导入依赖的package包/类
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, Object resObj) throws Exception {
try {
final JsonNode jsonNode = Jackson.valueToTree(resObj);
final String url = jsonNode.get("url").asText();
// Remove the url field and send it with the LOCATION header.
((ObjectNode) jsonNode).remove("url");
final HttpHeaders headers = HttpHeaders.of(HttpStatus.CREATED)
.add(HttpHeaderNames.LOCATION, url)
.contentType(MediaType.JSON_UTF_8);
return HttpResponse.of(headers, HttpData.of(Jackson.writeValueAsBytes(jsonNode)));
} catch (JsonProcessingException e) {
logger.debug("Failed to convert a response:", e);
return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
示例4: convertResponse
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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);
}
}
示例5: handleException
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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();
}
示例6: serve
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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);
}
示例7: configureThriftService
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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);
}
示例8: yummlyApi
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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);
}
示例9: httpResponse
import com.linecorp.armeria.common.HttpResponse; //导入依赖的package包/类
private static HttpResponse httpResponse(HttpData data) {
assert RequestContext.current() != null;
final HttpResponseWriter res = HttpResponse.streaming();
final long current = System.currentTimeMillis();
HttpHeaders headers = HttpHeaders.of(HttpStatus.OK)
.setInt(HttpHeaderNames.CONTENT_LENGTH,
data.length())
.setTimeMillis(HttpHeaderNames.DATE, current);
final MediaType contentType =
((ServiceRequestContext) RequestContext.current()).negotiatedProduceType();
if (contentType != null) {
headers.contentType(contentType);
}
res.write(headers);
res.write(data);
res.close();
return res;
}
示例10: testConcatenateRequestPath
import com.linecorp.armeria.common.HttpResponse; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Test
public void testConcatenateRequestPath() throws Exception {
String clientUriPath = "http://127.0.0.1/hello";
String requestPath = "world/test?q1=foo";
Client<HttpRequest, HttpResponse> mockClientDelegate = mock(Client.class);
ClientBuilderParams clientBuilderParams = new DefaultClientBuilderParams(ClientFactory.DEFAULT,
new URI(clientUriPath),
HttpClient.class,
ClientOptions.DEFAULT);
DefaultHttpClient defaultHttpClient = new DefaultHttpClient(clientBuilderParams,
mockClientDelegate,
NoopMeterRegistry.get(),
SessionProtocol.of("http"),
Endpoint.of("127.0.0.1"));
defaultHttpClient.execute(HttpRequest.of(HttpHeaders.of(HttpMethod.GET, requestPath)));
ArgumentCaptor<HttpRequest> httpRequestArgumentCaptor = ArgumentCaptor.forClass(HttpRequest.class);
verify(mockClientDelegate).execute(any(ClientRequestContext.class),
httpRequestArgumentCaptor.capture());
String concatPath = httpRequestArgumentCaptor.getValue().path();
assertThat(concatPath).isEqualTo("/hello/world/test?q1=foo");
}
示例11: testUnlimitedRequest
import com.linecorp.armeria.common.HttpResponse; //导入依赖的package包/类
@Test
public void testUnlimitedRequest() throws Exception {
final ClientRequestContext ctx = newContext();
final HttpRequest req = mock(HttpRequest.class);
final HttpResponseWriter actualRes = HttpResponse.streaming();
@SuppressWarnings("unchecked")
final Client<HttpRequest, HttpResponse> delegate = mock(Client.class);
when(delegate.execute(ctx, req)).thenReturn(actualRes);
final ConcurrencyLimitingHttpClient client =
newDecorator(0).apply(delegate);
// A request should be delegated immediately, creating no deferred response.
final HttpResponse res = client.execute(ctx, req);
verify(delegate).execute(ctx, req);
assertThat(res.isOpen()).isTrue();
assertThat(client.numActiveRequests()).isEqualTo(1);
// Complete the response, leaving no active requests.
closeAndDrain(actualRes, res);
await().untilAsserted(() -> assertThat(client.numActiveRequests()).isZero());
}
示例12: testThriftServiceRegistrationBean
import com.linecorp.armeria.common.HttpResponse; //导入依赖的package包/类
@Test
public void testThriftServiceRegistrationBean() throws Exception {
HelloService.Iface client = Clients.newClient(newUrl("tbinary+h1c") + "/thrift",
HelloService.Iface.class);
assertThat(client.hello("world")).isEqualTo("hello world");
HttpClient httpClient = HttpClient.of(newUrl("h1c"));
HttpResponse response = httpClient.get("/internal/docs/specification.json");
AggregatedHttpMessage msg = response.aggregate().get();
assertThat(msg.status()).isEqualTo(HttpStatus.OK);
assertThatJson(msg.content().toStringUtf8()).matches(
jsonPartMatches("services[0].exampleHttpHeaders[0].x-additional-header",
is("headerVal")));
}
示例13: json
import com.linecorp.armeria.common.HttpResponse; //导入依赖的package包/类
@Test
public void json() throws Exception {
AtomicReference<HttpHeaders> requestHeaders = new AtomicReference<>();
UnitTestServiceBlockingStub jsonStub =
new ClientBuilder(server.httpUri(GrpcSerializationFormats.JSON, "/"))
.decorator(HttpRequest.class, HttpResponse.class,
client -> new SimpleDecoratingClient<HttpRequest, HttpResponse>(client) {
@Override
public HttpResponse execute(ClientRequestContext ctx, HttpRequest req)
throws Exception {
requestHeaders.set(req.headers());
return delegate().execute(ctx, req);
}
})
.build(UnitTestServiceBlockingStub.class);
SimpleResponse response = jsonStub.staticUnaryCall(REQUEST_MESSAGE);
assertThat(response).isEqualTo(RESPONSE_MESSAGE);
assertThat(requestHeaders.get().get(HttpHeaderNames.CONTENT_TYPE)).isEqualTo("application/grpc+json");
}
示例14: missingMethod
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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[] {})));
}
示例15: serve
import com.linecorp.armeria.common.HttpResponse; //导入依赖的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;
}
};
}