Search in sources :

Example 1 with Handler

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

the class DefaultRatpackServer method buildAdapter.

protected NettyHandlerAdapter buildAdapter(DefinitionBuild definition) throws Exception {
    LOGGER.info("Building registry...");
    serverRegistry = buildServerRegistry(definition.getServerConfig(), definition.getUserRegistryFactory());
    Handler ratpackHandler = buildRatpackHandler(serverRegistry, definition.getHandlerFactory());
    ratpackHandler = decorateHandler(ratpackHandler, serverRegistry);
    servicesGraph = new ServicesGraph(serverRegistry);
    servicesGraph.start(new DefaultEvent(serverRegistry, reloading));
    return new NettyHandlerAdapter(serverRegistry, ratpackHandler);
}
Also used : DefaultEvent(ratpack.service.internal.DefaultEvent) ChunkedWriteHandler(io.netty.handler.stream.ChunkedWriteHandler) SslHandler(io.netty.handler.ssl.SslHandler) Handler(ratpack.handling.Handler) ServicesGraph(ratpack.service.internal.ServicesGraph)

Example 2 with Handler

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

the class NettyHandlerAdapter method newRequest.

private void newRequest(final ChannelHandlerContext ctx, final HttpRequest nettyRequest) throws Exception {
    if (!nettyRequest.decoderResult().isSuccess()) {
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;
    }
    Headers requestHeaders = new NettyHeadersBackedHeaders(nettyRequest.headers());
    //Find the content length we will use this as an indicator of a body
    Long contentLength = HttpUtil.getContentLength(nettyRequest, -1L);
    String transferEncoding = requestHeaders.get(HttpHeaderNames.TRANSFER_ENCODING);
    //If there is a content length or transfer encoding that indicates there is a body
    boolean hasBody = (contentLength > 0) || (transferEncoding != null);
    RequestBody requestBody = hasBody ? new RequestBody(contentLength, nettyRequest, ctx) : null;
    final Channel channel = ctx.channel();
    if (requestBody != null) {
        channel.attr(BODY_ACCUMULATOR_KEY).set(requestBody);
    }
    InetSocketAddress remoteAddress = (InetSocketAddress) channel.remoteAddress();
    InetSocketAddress socketAddress = (InetSocketAddress) channel.localAddress();
    final DefaultRequest request = new DefaultRequest(Instant.now(), requestHeaders, nettyRequest.method(), nettyRequest.protocolVersion(), nettyRequest.uri(), remoteAddress, socketAddress, serverRegistry.get(ServerConfig.class), requestBody);
    final HttpHeaders nettyHeaders = new DefaultHttpHeaders(false);
    final MutableHeaders responseHeaders = new NettyHeadersBackedMutableHeaders(nettyHeaders);
    final AtomicBoolean transmitted = new AtomicBoolean(false);
    final DefaultResponseTransmitter responseTransmitter = new DefaultResponseTransmitter(transmitted, channel, nettyRequest, request, nettyHeaders, requestBody);
    ctx.channel().attr(DefaultResponseTransmitter.ATTRIBUTE_KEY).set(responseTransmitter);
    Action<Action<Object>> subscribeHandler = thing -> {
        transmitted.set(true);
        ctx.channel().attr(CHANNEL_SUBSCRIBER_ATTRIBUTE_KEY).set(thing);
    };
    final DefaultContext.RequestConstants requestConstants = new DefaultContext.RequestConstants(applicationConstants, request, channel, responseTransmitter, subscribeHandler);
    final Response response = new DefaultResponse(responseHeaders, ctx.alloc(), responseTransmitter);
    requestConstants.response = response;
    DefaultContext.start(channel.eventLoop(), requestConstants, serverRegistry, handlers, execution -> {
        if (requestBody != null) {
            requestBody.close();
            channel.attr(BODY_ACCUMULATOR_KEY).set(null);
        }
        if (!transmitted.get()) {
            Handler lastHandler = requestConstants.handler;
            StringBuilder description = new StringBuilder();
            description.append("No response sent for ").append(request.getMethod().getName()).append(" request to ").append(request.getUri());
            if (lastHandler != null) {
                description.append(" (last handler: ");
                if (lastHandler instanceof DescribingHandler) {
                    ((DescribingHandler) lastHandler).describeTo(description);
                } else {
                    DescribingHandlers.describeTo(lastHandler, description);
                }
                description.append(")");
            }
            String message = description.toString();
            LOGGER.warn(message);
            response.getHeaders().clear();
            ByteBuf body;
            if (development) {
                CharBuffer charBuffer = CharBuffer.wrap(message);
                body = ByteBufUtil.encodeString(ctx.alloc(), charBuffer, CharsetUtil.UTF_8);
                response.contentType(HttpHeaderConstants.PLAIN_TEXT_UTF8);
            } else {
                body = Unpooled.EMPTY_BUFFER;
            }
            response.getHeaders().set(HttpHeaderConstants.CONTENT_LENGTH, body.readableBytes());
            responseTransmitter.transmit(HttpResponseStatus.INTERNAL_SERVER_ERROR, body);
        }
    });
}
Also used : AttributeKey(io.netty.util.AttributeKey) DescribingHandlers(ratpack.handling.internal.DescribingHandlers) LoggerFactory(org.slf4j.LoggerFactory) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Unpooled(io.netty.buffer.Unpooled) ByteBuf(io.netty.buffer.ByteBuf) MutableHeaders(ratpack.http.MutableHeaders) ServerConfig(ratpack.server.ServerConfig) Registry(ratpack.registry.Registry) CharsetUtil(io.netty.util.CharsetUtil) DefaultRenderController(ratpack.render.internal.DefaultRenderController) io.netty.channel(io.netty.channel) DefaultContext(ratpack.handling.internal.DefaultContext) Logger(org.slf4j.Logger) CharBuffer(java.nio.CharBuffer) ClosedChannelException(java.nio.channels.ClosedChannelException) ratpack.http.internal(ratpack.http.internal) ChainHandler(ratpack.handling.internal.ChainHandler) IOException(java.io.IOException) DescribingHandler(ratpack.handling.internal.DescribingHandler) Instant(java.time.Instant) InetSocketAddress(java.net.InetSocketAddress) ByteBufUtil(io.netty.buffer.ByteBufUtil) io.netty.handler.codec.http(io.netty.handler.codec.http) Response(ratpack.http.Response) Headers(ratpack.http.Headers) Action(ratpack.func.Action) Handler(ratpack.handling.Handler) Handlers(ratpack.handling.Handlers) ExecController(ratpack.exec.ExecController) Action(ratpack.func.Action) MutableHeaders(ratpack.http.MutableHeaders) Headers(ratpack.http.Headers) InetSocketAddress(java.net.InetSocketAddress) CharBuffer(java.nio.CharBuffer) ByteBuf(io.netty.buffer.ByteBuf) ServerConfig(ratpack.server.ServerConfig) MutableHeaders(ratpack.http.MutableHeaders) DescribingHandler(ratpack.handling.internal.DescribingHandler) ChainHandler(ratpack.handling.internal.ChainHandler) DescribingHandler(ratpack.handling.internal.DescribingHandler) Handler(ratpack.handling.Handler) Response(ratpack.http.Response) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) DefaultContext(ratpack.handling.internal.DefaultContext)

Example 3 with Handler

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

the class DescribingHandlers method describeTo.

public static void describeTo(Handler handler, StringBuilder stringBuilder) {
    Class<? extends Handler> clazz = handler.getClass();
    if (clazz.isAnonymousClass()) {
        ClassPool pool = ClassPool.getDefault();
        CtClass ctClass;
        try {
            ctClass = pool.get(clazz.getName());
            CtBehavior[] behaviors = ctClass.getDeclaredBehaviors();
            List<CtBehavior> withLineNumber = Arrays.asList(behaviors).stream().filter(input -> input.getMethodInfo().getLineNumber(0) > 0).sorted((o1, o2) -> Integer.valueOf(o1.getMethodInfo().getLineNumber(0)).compareTo(o2.getMethodInfo().getLineNumber(0))).collect(Collectors.toList());
            if (!withLineNumber.isEmpty()) {
                CtBehavior method = withLineNumber.get(0);
                int lineNumber = method.getMethodInfo().getLineNumber(0);
                ClassFile classFile = ctClass.getClassFile();
                String sourceFile = classFile.getSourceFile();
                if (lineNumber != -1 && sourceFile != null) {
                    stringBuilder.append("anonymous class ").append(clazz.getName()).append(" at approximately line ").append(lineNumber).append(" of ").append(sourceFile);
                    return;
                }
            }
        } catch (NotFoundException ignore) {
        // fall through
        }
    }
    stringBuilder.append(clazz.getName());
}
Also used : CtBehavior(javassist.CtBehavior) Arrays(java.util.Arrays) List(java.util.List) ClassFile(javassist.bytecode.ClassFile) Handler(ratpack.handling.Handler) NotFoundException(javassist.NotFoundException) CtBehavior(javassist.CtBehavior) CtClass(javassist.CtClass) Collectors(java.util.stream.Collectors) ClassPool(javassist.ClassPool) CtClass(javassist.CtClass) ClassFile(javassist.bytecode.ClassFile) ClassPool(javassist.ClassPool) NotFoundException(javassist.NotFoundException)

Example 4 with Handler

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

the class FactoryHandler method handle.

@Override
public void handle(Context context) throws Exception {
    Handler handler = factory.create();
    last = handler;
    handler.handle(context);
}
Also used : Handler(ratpack.handling.Handler)

Example 5 with Handler

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

the class DefaultFileHandlerSpec method build.

public static Handler build(ServerConfig serverConfig, Action<? super FileHandlerSpec> config) throws Exception {
    if (!serverConfig.isHasBaseDir()) {
        throw new BaseDirRequiredException("no base dir set for application");
    }
    DefaultFileHandlerSpec spec = new DefaultFileHandlerSpec();
    config.execute(spec);
    Handler handler = new FileHandler(spec.indexFiles, !serverConfig.isDevelopment());
    if (spec.dir != null) {
        handler = Handlers.fileSystem(serverConfig, spec.dir, handler);
    }
    if (spec.path != null) {
        handler = Handlers.prefix(spec.path, handler);
    }
    return handler;
}
Also used : BaseDirRequiredException(ratpack.file.BaseDirRequiredException) Handler(ratpack.handling.Handler)

Aggregations

Handler (ratpack.handling.Handler)8 Registry (ratpack.registry.Registry)3 ServerConfig (ratpack.server.ServerConfig)3 ByteBuf (io.netty.buffer.ByteBuf)2 CharsetUtil (io.netty.util.CharsetUtil)2 InetSocketAddress (java.net.InetSocketAddress)2 Instant (java.time.Instant)2 ClientErrorHandler (ratpack.error.ClientErrorHandler)2 ServerErrorHandler (ratpack.error.ServerErrorHandler)2 ExecController (ratpack.exec.ExecController)2 Action (ratpack.func.Action)2 Handlers (ratpack.handling.Handlers)2 MutableHeaders (ratpack.http.MutableHeaders)2 ImmutableMap (com.google.common.collect.ImmutableMap)1 HostAndPort (com.google.common.net.HostAndPort)1 ByteBufUtil (io.netty.buffer.ByteBufUtil)1 Unpooled (io.netty.buffer.Unpooled)1 Unpooled.buffer (io.netty.buffer.Unpooled.buffer)1 Unpooled.unreleasableBuffer (io.netty.buffer.Unpooled.unreleasableBuffer)1 io.netty.channel (io.netty.channel)1