Search in sources :

Example 1 with Context

use of ratpack.handling.Context in project ratpack by ratpack.

the class NewRelicExecInterceptor method intercept.

@Override
@Trace(dispatcher = true)
public void intercept(Execution execution, ExecType execType, Block executionSegment) throws Exception {
    execution.maybeGet(Context.class).ifPresent(context -> {
        NewRelicTransaction transaction = execution.maybeGet(NewRelicTransaction.class).orElse(null);
        if (transaction == null) {
            transaction = new DefaultNewRelicTransaction(context);
            execution.add(NewRelicTransaction.class, transaction);
        }
        transaction.init();
    });
    executionSegment.execute();
}
Also used : Context(ratpack.handling.Context) NewRelicTransaction(ratpack.newrelic.NewRelicTransaction) Trace(com.newrelic.api.agent.Trace)

Example 2 with Context

use of ratpack.handling.Context in project ratpack by ratpack.

the class Pac4jAuthenticator method createClients.

private Promise<Clients> createClients(Context ctx, PathBinding pathBinding) throws Exception {
    String boundTo = pathBinding.getBoundTo();
    PublicAddress publicAddress = ctx.get(PublicAddress.class);
    String absoluteCallbackUrl = publicAddress.get(b -> b.maybeEncodedPath(boundTo).maybeEncodedPath(path)).toASCIIString();
    Iterable<? extends Client<?, ?>> result = clientsProvider.get(ctx);
    @SuppressWarnings("rawtypes") List<Client> clients;
    if (result instanceof List) {
        clients = Types.cast(result);
    } else {
        clients = ImmutableList.copyOf(result);
    }
    return Promise.value(new Clients(absoluteCallbackUrl, clients));
}
Also used : Types(ratpack.util.Types) Context(ratpack.handling.Context) RatpackPac4j(ratpack.pac4j.RatpackPac4j) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) Promise(ratpack.exec.Promise) PublicAddress(ratpack.server.PublicAddress) Blocking(ratpack.exec.Blocking) RequiresHttpAction(org.pac4j.core.exception.RequiresHttpAction) WebContext(org.pac4j.core.context.WebContext) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) Clients(org.pac4j.core.client.Clients) Client(org.pac4j.core.client.Client) Handler(ratpack.handling.Handler) Registry(ratpack.registry.Registry) Optional(java.util.Optional) PathBinding(ratpack.path.PathBinding) TechnicalException(org.pac4j.core.exception.TechnicalException) UserProfile(org.pac4j.core.profile.UserProfile) SessionData(ratpack.session.SessionData) Credentials(org.pac4j.core.credentials.Credentials) List(java.util.List) ImmutableList(com.google.common.collect.ImmutableList) PublicAddress(ratpack.server.PublicAddress) Client(org.pac4j.core.client.Client) Clients(org.pac4j.core.client.Clients)

Example 3 with Context

use of ratpack.handling.Context in project ratpack by ratpack.

the class ServerSentEvents method render.

/**
   * {@inheritDoc}
   */
@Override
public void render(Context context) throws Exception {
    ByteBufAllocator bufferAllocator = context.get(ByteBufAllocator.class);
    Response response = context.getResponse();
    response.getHeaders().add(HttpHeaderConstants.CONTENT_TYPE, HttpHeaderConstants.TEXT_EVENT_STREAM_CHARSET_UTF_8);
    response.getHeaders().add(HttpHeaderConstants.TRANSFER_ENCODING, HttpHeaderConstants.CHUNKED);
    response.getHeaders().add(HttpHeaderConstants.CACHE_CONTROL, HttpHeaderConstants.NO_CACHE_FULL);
    response.getHeaders().add(HttpHeaderConstants.PRAGMA, HttpHeaderConstants.NO_CACHE);
    response.sendStream(Streams.map(publisher, i -> ServerSentEventEncoder.INSTANCE.encode(i, bufferAllocator)));
}
Also used : Response(ratpack.http.Response) Response(ratpack.http.Response) Context(ratpack.handling.Context) ServerSentEventEncoder(ratpack.sse.internal.ServerSentEventEncoder) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Action(ratpack.func.Action) Publisher(org.reactivestreams.Publisher) Renderable(ratpack.render.Renderable) Streams(ratpack.stream.Streams) HttpHeaderConstants(ratpack.http.internal.HttpHeaderConstants) DefaultEvent(ratpack.sse.internal.DefaultEvent) ByteBufAllocator(io.netty.buffer.ByteBufAllocator)

Example 4 with Context

use of ratpack.handling.Context in project ratpack by ratpack.

the class WebSockets method websocketBroadcast.

/**
   * Sets up a websocket that sends the published Strings to a client.
   * <p>
   * This takes the place of a {@link Streams#bindExec(Publisher)} call.
   *
   * @param context the request handling context
   * @param broadcaster a {@link Publisher} of Strings to send to the websocket client
   */
public static void websocketBroadcast(final Context context, final Publisher<String> broadcaster) {
    ByteBufAllocator bufferAllocator = context.get(ByteBufAllocator.class);
    websocketByteBufBroadcast(context, Streams.map(broadcaster, s -> ByteBufUtil.encodeString(bufferAllocator, CharBuffer.wrap(s), CharsetUtil.UTF_8)));
}
Also used : Function(ratpack.func.Function) Context(ratpack.handling.Context) CharBuffer(java.nio.CharBuffer) ByteBufAllocator(io.netty.buffer.ByteBufAllocator) Publisher(org.reactivestreams.Publisher) DefaultWebSocketConnector(ratpack.websocket.internal.DefaultWebSocketConnector) WebsocketBroadcastSubscriber(ratpack.websocket.internal.WebsocketBroadcastSubscriber) ByteBufUtil(io.netty.buffer.ByteBufUtil) ByteBuf(io.netty.buffer.ByteBuf) ServerConfig(ratpack.server.ServerConfig) WebSocketEngine(ratpack.websocket.internal.WebSocketEngine) CharsetUtil(io.netty.util.CharsetUtil) Streams(ratpack.stream.Streams) ByteBufAllocator(io.netty.buffer.ByteBufAllocator)

Example 5 with Context

use of ratpack.handling.Context in project ratpack by ratpack.

the class FormDecoder method parseForm.

@SuppressWarnings("deprecation")
public static Form parseForm(Context context, TypedData body, MultiValueMap<String, String> base) throws RuntimeException {
    Request request = context.getRequest();
    HttpMethod method = io.netty.handler.codec.http.HttpMethod.valueOf(request.getMethod().getName());
    HttpRequest nettyRequest = new DefaultHttpRequest(HttpVersion.HTTP_1_1, method, request.getUri());
    nettyRequest.headers().add(HttpHeaderNames.CONTENT_TYPE, body.getContentType().toString());
    HttpPostRequestDecoder decoder = new HttpPostRequestDecoder(nettyRequest);
    HttpContent content = new DefaultHttpContent(body.getBuffer());
    decoder.offer(content);
    decoder.offer(LastHttpContent.EMPTY_LAST_CONTENT);
    Map<String, List<String>> attributes = new LinkedHashMap<>(base.getAll());
    Map<String, List<UploadedFile>> files = new LinkedHashMap<>();
    try {
        InterfaceHttpData data = decoder.next();
        while (data != null) {
            if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.Attribute)) {
                List<String> values = attributes.get(data.getName());
                if (values == null) {
                    values = new ArrayList<>(1);
                    attributes.put(data.getName(), values);
                }
                try {
                    values.add(((Attribute) data).getValue());
                } catch (IOException e) {
                    throw uncheck(e);
                } finally {
                    data.release();
                }
            } else if (data.getHttpDataType().equals(InterfaceHttpData.HttpDataType.FileUpload)) {
                List<UploadedFile> values = files.get(data.getName());
                if (values == null) {
                    values = new ArrayList<>(1);
                    files.put(data.getName(), values);
                }
                try {
                    FileUpload nettyFileUpload = (FileUpload) data;
                    final ByteBuf byteBuf = nettyFileUpload.getByteBuf();
                    byteBuf.retain();
                    context.onClose(ro -> byteBuf.release());
                    MediaType contentType;
                    String rawContentType = nettyFileUpload.getContentType();
                    if (rawContentType == null) {
                        contentType = null;
                    } else {
                        Charset charset = nettyFileUpload.getCharset();
                        if (charset == null) {
                            contentType = DefaultMediaType.get(rawContentType);
                        } else {
                            contentType = DefaultMediaType.get(rawContentType + ";charset=" + charset);
                        }
                    }
                    UploadedFile fileUpload = new DefaultUploadedFile(new ByteBufBackedTypedData(byteBuf, contentType), nettyFileUpload.getFilename());
                    values.add(fileUpload);
                } catch (IOException e) {
                    throw uncheck(e);
                } finally {
                    data.release();
                }
            }
            data = decoder.next();
        }
    } catch (HttpPostRequestDecoder.EndOfDataDecoderException ignore) {
    // ignore
    } finally {
        decoder.destroy();
    }
    return new DefaultForm(new ImmutableDelegatingMultiValueMap<>(attributes), new ImmutableDelegatingMultiValueMap<>(files));
}
Also used : Context(ratpack.handling.Context) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) MultiValueMap(ratpack.util.MultiValueMap) Form(ratpack.form.Form) ImmutableDelegatingMultiValueMap(ratpack.util.internal.ImmutableDelegatingMultiValueMap) Exceptions.uncheck(ratpack.util.Exceptions.uncheck) DefaultMediaType(ratpack.http.internal.DefaultMediaType) IOException(java.io.IOException) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) UploadedFile(ratpack.form.UploadedFile) ArrayList(java.util.ArrayList) TypedData(ratpack.http.TypedData) LinkedHashMap(java.util.LinkedHashMap) Attribute(io.netty.handler.codec.http.multipart.Attribute) io.netty.handler.codec.http(io.netty.handler.codec.http) Request(ratpack.http.Request) List(java.util.List) ByteBuf(io.netty.buffer.ByteBuf) Charset(java.nio.charset.Charset) MediaType(ratpack.http.MediaType) ByteBufBackedTypedData(ratpack.http.internal.ByteBufBackedTypedData) Map(java.util.Map) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) ArrayList(java.util.ArrayList) ByteBuf(io.netty.buffer.ByteBuf) LinkedHashMap(java.util.LinkedHashMap) InterfaceHttpData(io.netty.handler.codec.http.multipart.InterfaceHttpData) DefaultMediaType(ratpack.http.internal.DefaultMediaType) MediaType(ratpack.http.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) ByteBufBackedTypedData(ratpack.http.internal.ByteBufBackedTypedData) FileUpload(io.netty.handler.codec.http.multipart.FileUpload) Request(ratpack.http.Request) Charset(java.nio.charset.Charset) IOException(java.io.IOException) HttpPostRequestDecoder(io.netty.handler.codec.http.multipart.HttpPostRequestDecoder) UploadedFile(ratpack.form.UploadedFile)

Aggregations

Context (ratpack.handling.Context)7 List (java.util.List)3 Exceptions.uncheck (ratpack.util.Exceptions.uncheck)3 ImmutableList (com.google.common.collect.ImmutableList)2 ByteBuf (io.netty.buffer.ByteBuf)2 ByteBufAllocator (io.netty.buffer.ByteBufAllocator)2 Optional (java.util.Optional)2 Client (org.pac4j.core.client.Client)2 Clients (org.pac4j.core.client.Clients)2 WebContext (org.pac4j.core.context.WebContext)2 Credentials (org.pac4j.core.credentials.Credentials)2 RequiresHttpAction (org.pac4j.core.exception.RequiresHttpAction)2 TechnicalException (org.pac4j.core.exception.TechnicalException)2 UserProfile (org.pac4j.core.profile.UserProfile)2 Publisher (org.reactivestreams.Publisher)2 Blocking (ratpack.exec.Blocking)2 Promise (ratpack.exec.Promise)2 Request (ratpack.http.Request)2 Streams (ratpack.stream.Streams)2 Throwables (com.google.common.base.Throwables)1