本文整理汇总了Java中com.linecorp.armeria.common.RequestContext类的典型用法代码示例。如果您正苦于以下问题:Java RequestContext类的具体用法?Java RequestContext怎么用?Java RequestContext使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
RequestContext类属于com.linecorp.armeria.common包,在下文中一共展示了RequestContext类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: convertResponse
import com.linecorp.armeria.common.RequestContext; //导入依赖的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);
}
}
示例2: handleException
import com.linecorp.armeria.common.RequestContext; //导入依赖的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();
}
示例3: scheduleTimeout
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
private <T> void scheduleTimeout(CompletableFuture<T> result, long timeoutMillis) {
pendingFutures.add(result);
if (isServerStopping()) {
pendingFutures.remove(result);
return;
}
final ScheduledFuture<?> timeoutFuture;
if (timeoutMillis > 0) {
final EventLoop eventLoop = RequestContext.current().eventLoop();
timeoutFuture = eventLoop.schedule(() -> result.completeExceptionally(CANCELLATION_EXCEPTION),
timeoutMillis, TimeUnit.MILLISECONDS);
} else {
timeoutFuture = null;
}
result.whenComplete((revision, cause) -> {
if (timeoutFuture != null) {
timeoutFuture.cancel(true);
}
pendingFutures.remove(result);
});
}
示例4: exportTlsProperties
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
private void exportTlsProperties(Map<String, String> out, RequestContext ctx) {
final SSLSession s = ctx.sslSession();
if (s != null) {
if (builtIns.contains(TLS_SESSION_ID)) {
final byte[] id = s.getId();
if (id != null) {
out.put(TLS_SESSION_ID.mdcKey, lowerCasedBase16.encode(id));
}
}
if (builtIns.contains(TLS_CIPHER)) {
final String cs = s.getCipherSuite();
if (cs != null) {
out.put(TLS_CIPHER.mdcKey, cs);
}
}
if (builtIns.contains(TLS_PROTO)) {
final String p = s.getProtocol();
if (p != null) {
out.put(TLS_PROTO.mdcKey, p);
}
}
}
}
示例5: testMdcPropertyPreservation
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
@Test
public void testMdcPropertyPreservation() throws Exception {
final List<ILoggingEvent> events = prepare(a -> a.addBuiltIn(BuiltInProperty.REQ_DIRECTION));
MDC.put("some-prop", "some-value");
final ServiceRequestContext ctx = newServiceContext("/foo", null);
try (SafeCloseable ignored = RequestContext.push(ctx)) {
final ILoggingEvent e = log(events);
final Map<String, String> mdc = e.getMDCPropertyMap();
assertThat(mdc).containsEntry("req.direction", "INBOUND")
.containsEntry("some-prop", "some-value")
.hasSize(2);
} finally {
MDC.remove("some-prop");
}
}
示例6: execute
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
/**
* Executes the specified {@link Request} via {@link #delegate()}.
*
* @param eventLoop the {@link EventLoop} to execute the {@link Request}
* @param method the method of the {@link Request}
* @param path the path part of the {@link Request} URI
* @param query the query part of the {@link Request} URI
* @param fragment the fragment part of the {@link Request} URI
* @param req the {@link Request}
* @param fallback the fallback response {@link Function} to use when
* {@link Client#execute(ClientRequestContext, Request)} of {@link #delegate()} throws
*/
protected final O execute(@Nullable EventLoop eventLoop,
HttpMethod method, String path, @Nullable String query, @Nullable String fragment,
I req, Function<Throwable, O> fallback) {
final ClientRequestContext ctx;
if (eventLoop == null) {
final ReleasableHolder<EventLoop> releasableEventLoop = factory().acquireEventLoop(endpoint);
ctx = new DefaultClientRequestContext(
releasableEventLoop.get(), meterRegistry, sessionProtocol, endpoint,
method, path, query, fragment, options(), req);
ctx.log().addListener(log -> releasableEventLoop.release(), RequestLogAvailability.COMPLETE);
} else {
ctx = new DefaultClientRequestContext(eventLoop, meterRegistry, sessionProtocol, endpoint,
method, path, query, fragment, options(), req);
}
try (SafeCloseable ignored = RequestContext.push(ctx)) {
return delegate().execute(ctx, req);
} catch (Throwable cause) {
ctx.logBuilder().endResponse(cause);
return fallback.apply(cause);
}
}
示例7: respond
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
private void respond(ChannelHandlerContext ctx, DecodedHttpRequest req, HttpStatus status,
RequestContext reqCtx, @Nullable Throwable cause) {
if (status.code() < 400) {
respond(ctx, req, AggregatedHttpMessage.of(HttpHeaders.of(status)), reqCtx, cause);
return;
}
final HttpData content;
if (req.method() == HttpMethod.HEAD || ArmeriaHttpUtil.isContentAlwaysEmpty(status)) {
content = HttpData.EMPTY_DATA;
} else {
content = status.toHttpData();
}
respond(ctx, req,
AggregatedHttpMessage.of(
HttpHeaders.of(status)
.contentType(ERROR_CONTENT_TYPE),
content), reqCtx, cause);
}
示例8: convertResponse
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
/**
* Converts the specified {@code result} to {@link HttpResponse}.
*/
private HttpResponse convertResponse(ServiceRequestContext ctx, Object result) {
if (result instanceof HttpResponse) {
return (HttpResponse) result;
}
if (result instanceof AggregatedHttpMessage) {
return HttpResponse.of((AggregatedHttpMessage) result);
}
try (SafeCloseable ignored = RequestContext.push(ctx, false)) {
for (final ResponseConverterFunction func : responseConverters) {
try {
return func.convertResponse(ctx, result);
} catch (FallthroughException ignore) {
// Do nothing.
} catch (Exception e) {
throw new IllegalStateException(
"Response converter " + func.getClass().getName() +
" cannot convert a result to HttpResponse: " + result, e);
}
}
}
throw new IllegalStateException(
"No response converter exists for a result: " +
result != null ? result.getClass().getSimpleName() : "(null)");
}
示例9: handleException
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
@Override
public HttpResponse handleException(RequestContext ctx, HttpRequest req, Throwable cause) {
if (cause instanceof IllegalArgumentException) {
return HttpResponse.of(HttpStatus.BAD_REQUEST);
}
if (cause instanceof HttpStatusException) {
return HttpResponse.of(((HttpStatusException) cause).httpStatus());
}
if (cause instanceof HttpResponseException) {
return ((HttpResponseException) cause).httpResponse();
}
return ExceptionHandlerFunction.DEFAULT.handleException(ctx, req, cause);
}
示例10: serve
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
@Override
public O serve(ServiceRequestContext ctx, I req) throws Exception {
final PathMappingContext mappingCtx = ctx.pathMappingContext();
final PathMapped<Service<I, O>> mapped = findService(mappingCtx.overridePath(ctx.mappedPath()));
if (!mapped.isPresent()) {
throw HttpStatusException.of(HttpStatus.NOT_FOUND);
}
final Optional<String> childPrefix = mapped.mapping().prefix();
if (childPrefix.isPresent()) {
final PathMapping newMapping = PathMapping.ofPrefix(ctx.pathMapping().prefix().get() +
childPrefix.get().substring(1));
final ServiceRequestContext newCtx = new CompositeServiceRequestContext(
ctx, newMapping, mapped.mappingResult().path());
try (SafeCloseable ignored = RequestContext.push(newCtx, false)) {
return mapped.value().serve(newCtx, req);
}
} else {
return mapped.value().serve(ctx, req);
}
}
示例11: setup
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
public static void setup(RequestContext ctx, MeterIdPrefixFunction meterIdPrefixFunction) {
if (ctx.hasAttr(ATTR_REQUEST_METRICS)) {
return;
}
// Set the attribute to the placeholder so that calling this method again has no effect.
// The attribute will be set to the real one later in onRequestStart()
ctx.attr(ATTR_REQUEST_METRICS).set(PLACEHOLDER);
ctx.log().addListener(log -> onRequestStart(log, meterIdPrefixFunction),
RequestLogAvailability.REQUEST_HEADERS,
RequestLogAvailability.REQUEST_CONTENT);
ctx.log().addListener(RequestMetricSupport::onRequestEnd,
RequestLogAvailability.REQUEST_END);
ctx.log().addListener(RequestMetricSupport::onResponse,
RequestLogAvailability.COMPLETE);
}
示例12: AbstractStreamMessageDuplicator
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
/**
* Creates a new instance wrapping a {@code publisher} and publishing to multiple subscribers.
* @param publisher the publisher who will publish data to subscribers
* @param signalLengthGetter the signal length getter that produces the length of signals
* @param executor the executor to use for upstream signals
* @param maxSignalLength the maximum length of signals. {@code 0} disables the length limit
*/
protected AbstractStreamMessageDuplicator(
U publisher, SignalLengthGetter<? super T> signalLengthGetter,
@Nullable EventExecutor executor, long maxSignalLength) {
requireNonNull(publisher, "publisher");
requireNonNull(signalLengthGetter, "signalLengthGetter");
checkArgument(maxSignalLength >= 0,
"maxSignalLength: %s (expected: >= 0)", maxSignalLength);
if (executor != null) {
duplicatorExecutor = executor;
} else {
duplicatorExecutor = RequestContext.mapCurrent(
RequestContext::eventLoop, () -> CommonPools.workerGroup().next());
}
processor = new StreamMessageProcessor<>(publisher, signalLengthGetter,
duplicatorExecutor, maxSignalLength);
}
示例13: convertResponse
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
@Override
public HttpResponse convertResponse(ServiceRequestContext ctx, Object resObj) throws Exception {
try {
final HttpRequest request = RequestContext.current().request();
final HttpData httpData =
resObj.getClass() == Object.class ? EMPTY_RESULT
: HttpData.of(Jackson.writeValueAsBytes(resObj));
return HttpResponse.of(HttpMethod.POST == request.method() ? HttpStatus.CREATED
: HttpStatus.OK,
MediaType.JSON_UTF_8,
httpData);
} catch (JsonProcessingException e) {
return HttpResponse.of(HttpStatus.INTERNAL_SERVER_ERROR);
}
}
示例14: recipe
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
@Produces
static ListenableFuture<Recipe> recipe(
List<String> ingredients,
SearchResponse searchResponse,
Supplier<Random> randomSupplier,
YummlyApi yummly) {
int totalCount = searchResponse.totalMatchCount();
ListenableFuture<SearchResponse> future = Futures.immediateFuture(null);
// Get a random recipe to return. Search request fails randomly so try a few times.
Executor executor = RequestContext.current().contextAwareEventLoop();
Random random = randomSupplier.get();
for (int i = 0; i < 5; i++) {
int resultIndex = random.nextInt(totalCount);
future =
Futures.transformAsync(
future,
result -> {
if (result != null && !result.matches().isEmpty()) {
return Futures.immediateFuture(result);
}
return yummly.search(
EggworldConstants.EGG_QUERY,
ingredients,
resultIndex,
1,
true,
ImmutableList.of());
},
executor);
}
return Futures.transform(future, r -> r.matches().get(0), MoreExecutors.directExecutor());
}
示例15: exportAddresses
import com.linecorp.armeria.common.RequestContext; //导入依赖的package包/类
private void exportAddresses(Map<String, String> out, RequestContext ctx) {
final InetSocketAddress raddr = ctx.remoteAddress();
final InetSocketAddress laddr = ctx.localAddress();
if (raddr != null) {
if (builtIns.contains(REMOTE_HOST)) {
out.put(REMOTE_HOST.mdcKey, raddr.getHostString());
}
if (builtIns.contains(REMOTE_IP)) {
out.put(REMOTE_IP.mdcKey, raddr.getAddress().getHostAddress());
}
if (builtIns.contains(REMOTE_PORT)) {
out.put(REMOTE_PORT.mdcKey, String.valueOf(raddr.getPort()));
}
}
if (laddr != null) {
if (builtIns.contains(LOCAL_HOST)) {
out.put(LOCAL_HOST.mdcKey, laddr.getHostString());
}
if (builtIns.contains(LOCAL_IP)) {
out.put(LOCAL_IP.mdcKey, laddr.getAddress().getHostAddress());
}
if (builtIns.contains(LOCAL_PORT)) {
out.put(LOCAL_PORT.mdcKey, String.valueOf(laddr.getPort()));
}
}
}