Example usage for io.netty.channel ChannelHandlerContext executor

List of usage examples for io.netty.channel ChannelHandlerContext executor

Introduction

In this page you can find the example usage for io.netty.channel ChannelHandlerContext executor.

Prototype

EventExecutor executor();

Source Link

Document

Returns the EventExecutor which is used to execute an arbitrary task.

Usage

From source file:io.pravega.shared.protocol.netty.CommandEncoder.java

License:Open Source License

@Override
protected void encode(ChannelHandlerContext ctx, Object msg, ByteBuf out) throws Exception {
    log.trace("Encoding message to send over the wire {}", msg);
    if (msg instanceof Append) {
        Append append = (Append) msg;/*from  ww  w .j  a  v a2  s  . c  o  m*/
        Session session = setupSegments.get(append.segment);
        if (session == null || !session.id.equals(append.getConnectionId())) {
            throw new InvalidMessageException("Sending appends without setting up the append.");
        }
        if (append.getEventNumber() <= session.lastEventNumber) {
            throw new InvalidMessageException("Events written out of order. Received: "
                    + append.getEventNumber() + " following: " + session.lastEventNumber);
        }
        if (append.isConditional()) {
            breakFromAppend(out);
            ConditionalAppend ca = new ConditionalAppend(append.connectionId, append.eventNumber,
                    append.getExpectedLength(), wrappedBuffer(serializeMessage(new Event(append.getData()))));
            writeMessage(ca, out);
        } else {
            Preconditions.checkState(bytesLeftInBlock == 0 || bytesLeftInBlock > TYPE_PLUS_LENGTH_SIZE,
                    "Bug in CommandEncoder.encode, block is too small.");
            if (append.segment != segmentBeingAppendedTo) {
                breakFromAppend(out);
            }
            if (bytesLeftInBlock == 0) {
                currentBlockSize = Math.max(TYPE_PLUS_LENGTH_SIZE, blockSizeSupplier.getAppendBlockSize());
                bytesLeftInBlock = currentBlockSize;
                segmentBeingAppendedTo = append.segment;
                writeMessage(new AppendBlock(session.id), out);
                if (ctx != null) {
                    ctx.executor().schedule(new Flusher(ctx.channel(), currentBlockSize),
                            blockSizeSupplier.getBatchTimeout(), TimeUnit.MILLISECONDS);
                }
            }

            session.lastEventNumber = append.getEventNumber();
            session.eventCount++;
            ByteBuf data = append.getData();
            int msgSize = TYPE_PLUS_LENGTH_SIZE + data.readableBytes();
            // Is there enough space for a subsequent message after this one?
            if (bytesLeftInBlock - msgSize > TYPE_PLUS_LENGTH_SIZE) {
                bytesLeftInBlock -= writeMessage(new Event(data), out);
            } else {
                byte[] serializedMessage = serializeMessage(new Event(data));
                int bytesInBlock = bytesLeftInBlock - TYPE_PLUS_LENGTH_SIZE;
                ByteBuf dataInsideBlock = wrappedBuffer(serializedMessage, 0, bytesInBlock);
                ByteBuf dataRemainging = wrappedBuffer(serializedMessage, bytesInBlock,
                        serializedMessage.length - bytesInBlock);
                writeMessage(new PartialEvent(dataInsideBlock), out);
                writeMessage(new AppendBlockEnd(session.id, currentBlockSize - bytesLeftInBlock, dataRemainging,
                        session.eventCount, session.lastEventNumber, 0L), out);
                bytesLeftInBlock = 0;
                session.eventCount = 0;
            }
        }
    } else if (msg instanceof SetupAppend) {
        breakFromAppend(out);
        writeMessage((SetupAppend) msg, out);
        SetupAppend setup = (SetupAppend) msg;
        setupSegments.put(setup.getSegment(), new Session(setup.getConnectionId()));
    } else if (msg instanceof Flush) {
        Flush flush = (Flush) msg;
        if (currentBlockSize == flush.getBlockSize()) {
            breakFromAppend(out);
        }
    } else if (msg instanceof WireCommand) {
        breakFromAppend(out);
        writeMessage((WireCommand) msg, out);
    } else {
        throw new IllegalArgumentException("Expected a wire command and found: " + msg);
    }
}

From source file:io.reactivex.netty.pipeline.ReadTimeoutPipelineConfigurator.java

License:Apache License

public static void disableReadTimeout(ChannelPipeline pipeline) {

    /**/* www.  ja  va 2  s  . co  m*/
     * Since, ChannelPipeline.remove() is blocking when not called from the associated eventloop, we do not remove
     * the handler. Instead we decativate the handler (invoked by the associated eventloop) here so that it does not
     * generate any more timeouts.
     * The handler is activated on next write to this pipeline.
     *
     * See issue: https://github.com/Netflix/RxNetty/issues/145
     */
    final ChannelHandler timeoutHandler = pipeline.get(READ_TIMEOUT_HANDLER_NAME);
    if (timeoutHandler != null) {
        final ChannelHandlerContext handlerContext = pipeline.context(timeoutHandler);
        EventExecutor executor = handlerContext.executor();

        // Since, we are calling the handler directly, we need to make sure, it is in the owner eventloop, else it
        // can get concurrent callbacks.
        if (executor.inEventLoop()) {
            disableHandler(timeoutHandler, handlerContext);
        } else {
            executor.submit(new Callable<Object>() {

                @Override
                public Object call() throws Exception {
                    disableHandler(timeoutHandler, handlerContext);
                    return null;
                }
            });
        }
    }
}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void handleGET(final ChannelHandlerContext ctx, final ObjectRequest objectRequest) throws Exception {

    log.info("handleGET req: {}", httpRequest);

    mds.list(ctx.executor(), objectRequest).addListener(new GenericFutureListener<Future<ObjectResponse>>() {
        @Override//from   w w  w .  j a v a  2 s.c  om
        public void operationComplete(Future<ObjectResponse> future) throws Exception {
            if (!future.isSuccess()) {
                log.error("future failed for handleGET: {}", objectRequest, future.cause());
                sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                return;
            }

            ObjectResponse objectResponse = future.getNow();

            log.info("result of mds.operate: {} -> {}", objectRequest, objectResponse);

            if (objectResponse instanceof ObjectResponse.EmptyResponse) {
                log.info("nothing found at: {}", objectRequest);
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;

            }

            if (objectResponse instanceof ObjectResponse.SingleObject) {
                log.info("GET is for a file. proxy for downloading: {}", objectResponse);
                setupProxyToGET(ctx, ((ObjectResponse.SingleObject) objectResponse).fullObjectName);
                return;

            }

            if (!(objectResponse instanceof ObjectResponse.MultipleObjects)) {
                log.info("multipleObjects.objects is not MultipleObjects: {}", objectResponse);
                sendError(ctx, HttpResponseStatus.NOT_FOUND);
                return;
            }

            log.info("returning result of mds.list: {}", objectResponse.json());
            ctx.writeAndFlush(objectResponse.encode(), ctx.voidPromise());
        }
    });
}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void handleDELETE(final ChannelHandlerContext ctx, final ObjectRequest request) throws IOException {
    log.info("handleDELETE req: {}", httpRequest);

    mds.delete(ctx.executor(), request).addListener(new GenericFutureListener<Future<ObjectResponse>>() {
        @Override/*from  w ww.  ja  va 2  s . com*/
        public void operationComplete(Future<ObjectResponse> future) throws Exception {
            if (future.isSuccess()) {
                ObjectResponse response = future.get();
                if (response instanceof ObjectResponse.Failure) {
                    log.warn("error on handleDELETE: {} -> {}", request, response);
                    sendError(ctx, response.encode());
                } else {
                    log.info("successful handleDELETE req: {}, rsp: {}", request, response);
                    ctx.writeAndFlush(response.encode());
                }
            } else {
                log.warn("error on handleDELETE: {}", request, future.cause());
                sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            }
        }
    });

}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void handleHEAD(final ChannelHandlerContext ctx, final ObjectRequest objectRequest) {

    log.info("handleHEAD uri: {} ", httpRequest.getUri());

    mds.head(ctx.executor(), objectRequest).addListener(new GenericFutureListener<Future<ObjectResponse>>() {
        @Override/*ww  w  .j  a v  a  2  s . c  om*/
        public void operationComplete(Future<ObjectResponse> future) throws Exception {
            if (future.isSuccess()) {
                ObjectResponse objectResponse = future.get();

                log.info("handleHEAD {} -> {}", objectRequest, objectResponse);

                // todo: use .encode()
                if (objectResponse instanceof ObjectResponse.SingleObject) {
                    ObjectResponse.SingleObject singleObject = (ObjectResponse.SingleObject) objectResponse;

                    FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1,
                            HttpResponseStatus.NO_CONTENT);

                    if (singleObject.fullObjectName.attributes.dir) {
                        response.headers().set(CONTENT_TYPE, "application/x-json-stream; type=directory");
                    } else {
                        response.headers().set(CONTENT_MD5, singleObject.fullObjectName.attributes.md5);
                    }

                    ctx.writeAndFlush(response).addListener(new GenericFutureListener<ChannelFuture>() {

                        @Override
                        public void operationComplete(ChannelFuture future) throws Exception {
                            if (future.isSuccess()) {
                                log.info("write success");
                            } else {
                                log.info("write failed: {}", future.cause());
                            }

                        }
                    });

                    return;
                }

                log.warn("error on handleHEAD: {}", objectRequest, future.cause());
                sendError(ctx, ERROR_BAD_REQUEST);
            }
        }
    });

}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void handlePUTmkdir(final ChannelHandlerContext ctx, ObjectRequest request) throws Exception {
    if (request.isNotDirectory()) {
        log.warn("request is not mkdir: {}", request);
        sendError(ctx, HttpResponseStatus.BAD_REQUEST);
        return;//from  w  w w .ja va2 s  .c o  m
    }

    log.info("this is a mkdir: {}", request);
    ExtendedObjectAttributes eoa = new ExtendedObjectAttributes(true, 0, "", uuid.next(), 1,
            System.currentTimeMillis());
    final FullObjectRequest fullObjectRequest = new FullObjectRequest(request, eoa);
    mds.put(ctx.executor(), fullObjectRequest).addListener(new GenericFutureListener<Future<ObjectResponse>>() {
        @Override
        public void operationComplete(Future<ObjectResponse> future) throws Exception {
            if (future.isSuccess()) {
                ObjectResponse response = future.getNow();
                log.info("successful mkdir: {}", response);
                ctx.writeAndFlush(
                        new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NO_CONTENT),
                        ctx.voidPromise());
                ctx.channel().close();
            } else {
                log.warn("no success on mkdir: {}", future.cause());
                sendError(ctx, HttpResponseStatus.BAD_REQUEST);
            }
        }
    });
}

From source file:io.urmia.api.handler.RestApiHandler.java

License:Open Source License

private void setupProxyToGET(final ChannelHandlerContext ctx, final FullObjectName fon) throws Exception {

    log.info("proxy GET storage node: download mode: {}", true);

    final Future<List<String>> futureStorageNodes = mds.storedNodes(ctx.executor(), fon.attributes.etag);

    futureStorageNodes.addListener(new GenericFutureListener<Future<List<String>>>() {
        @Override/*  w w  w  . j  ava2  s . co m*/
        public void operationComplete(Future<List<String>> future) throws Exception {
            if (future.isSuccess()) {
                final List<String> st = future.getNow();

                Optional<ServiceInstance<NodeType>> si = findStorageInstanceUp(st);

                if (!si.isPresent()) {
                    log.error("failed to find running node, req: {}", objectRequest);
                    sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
                    return;
                }

                List<ServiceInstance<NodeType>> l = Lists.newArrayList(si.get());
                log.info("proxy storage node: {}, download mode: {}, durability: {}", st, true,
                        objectRequest.getDurability());
                HttpProxyFrontendHandler proxy = new HttpProxyFrontendHandler(l, mds, httpRequest, ctx, true,
                        Optional.<FullObjectName>absent());

                ctx.pipeline().remove("encoder");

                ctx.pipeline().addLast("proxy", proxy);

                proxyMode = true;

                ctx.read(); // todo: can ve removed?

            } else {
                log.error("failed to fetch futureStorageNodes, req: {}", objectRequest, future.cause());
                sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
            }
        }
    });

}

From source file:io.urmia.proxy.HttpProxyFrontendHandler.java

License:Open Source License

private void onComplete(final ChannelHandlerContext ctx, final int index) {
    log.info("onComplete: {}", index);

    completedSet.set(index);/*from w w  w  .  j av  a 2 s .com*/

    mds.flagStored(ctx.executor(), storageNodes.get(index).getId(), etag);

    if (completedSet.cardinality() != outboundCount)
        return;

    log.info("all onComplete");

    final String md5;
    final long size;

    if (fon.isPresent()) {
        md5 = fon.get().attributes.md5;
        size = fon.get().attributes.size;

        digestFinal();
    } else {
        // todo: for mln copy md5 and size from original object
        md5 = digestFinal();
        log.info("md5: ", md5);

        size = receivedSize.longValue();
        receivedSize.set(0);
        log.info("size: {}", size);
    }

    ExtendedObjectAttributes eoa = new ExtendedObjectAttributes(false, size, md5, etag.value,
            completedSet.cardinality(), System.currentTimeMillis());
    final FullObjectRequest req = new FullObjectRequest(objectRequest, eoa);

    log.info("mds.put: {}", req);

    mds.put(ctx.executor(), req).addListener(new GenericFutureListener<Future<ObjectResponse>>() {
        @Override
        public void operationComplete(Future<ObjectResponse> future) throws Exception {
            HttpResponseStatus status = future.isSuccess() ? HttpResponseStatus.OK
                    : HttpResponseStatus.BAD_GATEWAY;

            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status);
            log.info("writing back to client: {}", response);
            ctx.writeAndFlush(response).addListener(new GenericFutureListener<ChannelFuture>() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    log.info("write back successful. closing channel");
                    ctx.channel().close();
                }
            });
        }
    });
}

From source file:io.vertx.core.net.impl.VertxSniHandler.java

License:Open Source License

public VertxSniHandler(SSLHelper helper, VertxInternal vertx) {
    super(input -> {
        return helper.getContext(vertx, input);
    });/*from w ww. j a  v  a2 s.co  m*/
    this.helper = helper;
    this.handshakeFuture = new DefaultPromise<Channel>() {
        @Override
        protected EventExecutor executor() {
            ChannelHandlerContext ctx = context;
            if (ctx == null) {
                throw new IllegalStateException();
            }
            return ctx.executor();
        }
    };
}

From source file:io.werval.server.netty.WervalHttpHandler.java

License:Apache License

@Override
protected void channelRead0(ChannelHandlerContext nettyContext, FullHttpRequest nettyRequest) throws Exception {
    // Get the request unique identifier
    requestIdentity = nettyContext.channel().attr(Attrs.REQUEST_IDENTITY).get();
    assert requestIdentity != null;
    if (LOG.isTraceEnabled()) {
        LOG.trace("{} Received a FullHttpRequest:\n{}", requestIdentity, nettyRequest.toString());
    }/*from   w  ww  . ja  v a  2s.c  o  m*/

    // Return 503 to incoming requests while shutting down
    if (nettyContext.executor().isShuttingDown()) {
        app.shuttingDownOutcome(ProtocolVersion.valueOf(nettyRequest.getProtocolVersion().text()),
                requestIdentity).thenAcceptAsync(shuttingDownOutcome -> {
                    writeOutcome(nettyContext, shuttingDownOutcome).addListeners(
                            new HttpRequestCompleteChannelFutureListener(requestHeader),
                            f -> app.events().emit(new HttpEvent.ResponseSent(requestIdentity,
                                    shuttingDownOutcome.responseHeader().status())));
                }, app.executor());
        return;
    }

    // In development mode, rebuild application source if needed
    if (devSpi != null && devSpi.isSourceChanged()) {
        devSpi.rebuild();
    }

    // Create Request Instance
    // Can throw HttpRequestParsingException
    Request request = requestOf(app.defaultCharset(), app.httpBuilders(),
            remoteAddressOf(nettyContext.channel()), requestIdentity, nettyRequest);
    requestHeader = request;

    // Handle Request
    app.handleRequest(request).thenAcceptAsync(outcome -> {
        // Write Outcome
        ChannelFuture writeFuture = writeOutcome(nettyContext, outcome);
        // Listen to request completion
        writeFuture.addListeners(
                f -> app.events()
                        .emit(new HttpEvent.ResponseSent(requestIdentity, outcome.responseHeader().status())),
                new HttpRequestCompleteChannelFutureListener(requestHeader));
    }, app.executor());
}