Example usage for io.netty.channel ChannelPromise setFailure

List of usage examples for io.netty.channel ChannelPromise setFailure

Introduction

In this page you can find the example usage for io.netty.channel ChannelPromise setFailure.

Prototype

@Override
    ChannelPromise setFailure(Throwable cause);

Source Link

Usage

From source file:org.apache.hadoop.hbase.ipc.TestAsyncIPC.java

License:Apache License

@Override
protected AsyncRpcClient createRpcClientRTEDuringConnectionSetup(Configuration conf) {
    setConf(conf);/*from w w  w  .java 2  s  . c  om*/
    return new AsyncRpcClient(conf, HConstants.CLUSTER_ID_DEFAULT, null,
            new ChannelInitializer<SocketChannel>() {

                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            promise.setFailure(new RuntimeException("Injected fault"));
                        }
                    });
                }
            });
}

From source file:org.apache.hadoop.hbase.ipc.TestIPC.java

License:Apache License

@Test
public void testRTEDuringAsyncBlockingConnectionSetup() throws Exception {
    Configuration conf = HBaseConfiguration.create();

    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = new AsyncRpcClient(conf, HConstants.CLUSTER_ID_DEFAULT, null,
            new ChannelInitializer<SocketChannel>() {

                @Override//from  w ww.ja v a  2s .c  om
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            promise.setFailure(new RuntimeException("Injected fault"));
                        }
                    });
                }
            });
    try {
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        BlockingRpcChannel channel = client.createBlockingRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        channel.callBlockingMethod(md, new PayloadCarryingRpcController(), param, md.getOutputType().toProto());

        fail("Expected an exception to have been thrown!");
    } catch (Exception e) {
        LOG.info("Caught expected exception: " + e.toString());
        assertTrue(StringUtils.stringifyException(e).contains("Injected fault"));
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:org.apache.hadoop.hbase.ipc.TestIPC.java

License:Apache License

@Test
public void testRTEDuringAsyncConnectionSetup() throws Exception {
    Configuration conf = HBaseConfiguration.create();

    TestRpcServer rpcServer = new TestRpcServer();
    AsyncRpcClient client = new AsyncRpcClient(conf, HConstants.CLUSTER_ID_DEFAULT, null,
            new ChannelInitializer<SocketChannel>() {

                @Override//from w  ww  .  j a va2 s  .c om
                protected void initChannel(SocketChannel ch) throws Exception {
                    ch.pipeline().addFirst(new ChannelOutboundHandlerAdapter() {
                        @Override
                        public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise)
                                throws Exception {
                            promise.setFailure(new RuntimeException("Injected fault"));
                        }
                    });
                }
            });
    try {
        rpcServer.start();
        InetSocketAddress address = rpcServer.getListenerAddress();
        MethodDescriptor md = SERVICE.getDescriptorForType().findMethodByName("echo");
        EchoRequestProto param = EchoRequestProto.newBuilder().setMessage("hello").build();

        RpcChannel channel = client.createRpcChannel(
                ServerName.valueOf(address.getHostName(), address.getPort(), System.currentTimeMillis()),
                User.getCurrent(), 0);

        final AtomicBoolean done = new AtomicBoolean(false);

        PayloadCarryingRpcController controller = new PayloadCarryingRpcController();
        controller.notifyOnFail(new RpcCallback<IOException>() {
            @Override
            public void run(IOException e) {
                done.set(true);
                LOG.info("Caught expected exception: " + e.toString());
                assertTrue(StringUtils.stringifyException(e).contains("Injected fault"));
            }
        });

        channel.callMethod(md, controller, param, md.getOutputType().toProto(), new RpcCallback<Message>() {
            @Override
            public void run(Message parameter) {
                done.set(true);
                fail("Expected an exception to have been thrown!");
            }
        });

        TEST_UTIL.waitFor(1000, new Waiter.Predicate<Exception>() {
            @Override
            public boolean evaluate() throws Exception {
                return done.get();
            }
        });
    } finally {
        client.close();
        rpcServer.stop();
    }
}

From source file:org.apache.hadoop.hbase.security.SaslClientHandler.java

License:Apache License

@Override
public void write(final ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
    // If not complete, try to negotiate
    if (!saslClient.isComplete()) {
        super.write(ctx, msg, promise);
    } else {//www .ja  v  a2 s.  com
        ByteBuf in = (ByteBuf) msg;

        try {
            saslToken = saslClient.wrap(in.array(), in.readerIndex(), in.readableBytes());
        } catch (SaslException se) {
            try {
                saslClient.dispose();
            } catch (SaslException ignored) {
                LOG.debug("Ignoring SASL exception", ignored);
            }
            promise.setFailure(se);
        }
        if (saslToken != null) {
            ByteBuf out = ctx.channel().alloc().buffer(4 + saslToken.length);
            out.writeInt(saslToken.length);
            out.writeBytes(saslToken, 0, saslToken.length);

            ctx.write(out).addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        exceptionCaught(ctx, future.cause());
                    }
                }
            });

            saslToken = null;
        }
    }
}

From source file:org.apache.tinkerpop.gremlin.server.handler.HttpGremlinEndpointHandler.java

License:Apache License

@Override
public void channelRead(final ChannelHandlerContext ctx, final Object msg) {
    if (msg instanceof FullHttpRequest) {
        final FullHttpRequest req = (FullHttpRequest) msg;

        if ("/favicon.ico".equals(req.getUri())) {
            sendError(ctx, NOT_FOUND, "Gremlin Server doesn't have a favicon.ico");
            ReferenceCountUtil.release(msg);
            return;
        }/*w w w.j  a va2 s.  c o  m*/

        if (is100ContinueExpected(req)) {
            ctx.write(new DefaultFullHttpResponse(HTTP_1_1, CONTINUE));
        }

        if (req.getMethod() != GET && req.getMethod() != POST) {
            sendError(ctx, METHOD_NOT_ALLOWED, METHOD_NOT_ALLOWED.toString());
            ReferenceCountUtil.release(msg);
            return;
        }

        final Quartet<String, Map<String, Object>, String, Map<String, String>> requestArguments;
        try {
            requestArguments = getRequestArguments(req);
        } catch (IllegalArgumentException iae) {
            sendError(ctx, BAD_REQUEST, iae.getMessage());
            ReferenceCountUtil.release(msg);
            return;
        }

        final String acceptString = Optional.ofNullable(req.headers().get("Accept")).orElse("application/json");
        final Pair<String, MessageTextSerializer> serializer = chooseSerializer(acceptString);
        if (null == serializer) {
            sendError(ctx, BAD_REQUEST,
                    String.format("no serializer for requested Accept header: %s", acceptString));
            ReferenceCountUtil.release(msg);
            return;
        }

        final String origin = req.headers().get(ORIGIN);
        final boolean keepAlive = isKeepAlive(req);

        // not using the req any where below here - assume it is safe to release at this point.
        ReferenceCountUtil.release(msg);

        try {
            logger.debug("Processing request containing script [{}] and bindings of [{}] on {}",
                    requestArguments.getValue0(), requestArguments.getValue1(),
                    Thread.currentThread().getName());
            final ChannelPromise promise = ctx.channel().newPromise();
            final AtomicReference<Object> resultHolder = new AtomicReference<>();
            promise.addListener(future -> {
                // if failed then the error was already written back to the client as part of the eval future
                // processing of the exception
                if (future.isSuccess()) {
                    logger.debug(
                            "Preparing HTTP response for request with script [{}] and bindings of [{}] with result of [{}] on [{}]",
                            requestArguments.getValue0(), requestArguments.getValue1(), resultHolder.get(),
                            Thread.currentThread().getName());
                    final FullHttpResponse response = new DefaultFullHttpResponse(HTTP_1_1, OK,
                            (ByteBuf) resultHolder.get());
                    response.headers().set(CONTENT_TYPE, serializer.getValue0());
                    response.headers().set(CONTENT_LENGTH, response.content().readableBytes());

                    // handle cors business
                    if (origin != null)
                        response.headers().set(ACCESS_CONTROL_ALLOW_ORIGIN, origin);

                    if (!keepAlive) {
                        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
                    } else {
                        response.headers().set(CONNECTION, HttpHeaders.Values.KEEP_ALIVE);
                        ctx.writeAndFlush(response);
                    }
                }
            });

            final Timer.Context timerContext = evalOpTimer.time();

            final Bindings bindings;
            try {
                bindings = createBindings(requestArguments.getValue1(), requestArguments.getValue3());
            } catch (IllegalStateException iae) {
                sendError(ctx, BAD_REQUEST, iae.getMessage());
                ReferenceCountUtil.release(msg);
                return;
            }

            // provide a transform function to serialize to message - this will force serialization to occur
            // in the same thread as the eval. after the CompletableFuture is returned from the eval the result
            // is ready to be written as a ByteBuf directly to the response.  nothing should be blocking here.
            final CompletableFuture<Object> evalFuture = gremlinExecutor.eval(requestArguments.getValue0(),
                    requestArguments.getValue2(), bindings, FunctionUtils.wrapFunction(o -> {
                        // stopping the timer here is roughly equivalent to where the timer would have been stopped for
                        // this metric in other contexts.  we just want to measure eval time not serialization time.
                        timerContext.stop();

                        logger.debug(
                                "Transforming result of request with script [{}] and bindings of [{}] with result of [{}] on [{}]",
                                requestArguments.getValue0(), requestArguments.getValue1(), o,
                                Thread.currentThread().getName());
                        final ResponseMessage responseMessage = ResponseMessage.build(UUID.randomUUID())
                                .code(ResponseStatusCode.SUCCESS).result(IteratorUtils.asList(o)).create();

                        // http server is sessionless and must handle commit on transactions. the commit occurs
                        // before serialization to be consistent with how things work for websocket based
                        // communication.  this means that failed serialization does not mean that you won't get
                        // a commit to the database
                        attemptCommit(requestArguments.getValue3(), graphManager,
                                settings.strictTransactionManagement);

                        try {
                            return Unpooled.wrappedBuffer(serializer.getValue1()
                                    .serializeResponseAsString(responseMessage).getBytes(UTF8));
                        } catch (Exception ex) {
                            logger.warn(String.format("Error during serialization for %s", responseMessage),
                                    ex);
                            throw ex;
                        }
                    }));

            evalFuture.exceptionally(t -> {
                if (t.getMessage() != null)
                    sendError(ctx, INTERNAL_SERVER_ERROR, t.getMessage(), Optional.of(t));
                else
                    sendError(ctx, INTERNAL_SERVER_ERROR, String
                            .format("Error encountered evaluating script: %s", requestArguments.getValue0()),
                            Optional.of(t));
                promise.setFailure(t);
                return null;
            });

            evalFuture.thenAcceptAsync(r -> {
                // now that the eval/serialization is done in the same thread - complete the promise so we can
                // write back the HTTP response on the same thread as the original request
                resultHolder.set(r);
                promise.setSuccess();
            }, gremlinExecutor.getExecutorService());
        } catch (Exception ex) {
            // tossed to exceptionCaught which delegates to sendError method
            final Throwable t = ExceptionUtils.getRootCause(ex);
            throw new RuntimeException(null == t ? ex : t);
        }
    }
}

From source file:org.dcache.xrootd.protocol.messages.AbstractXrootdResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, ChannelPromise promise) {
    int dlen = getDataLength();
    ByteBuf buffer = ctx.alloc().buffer(8 + dlen);
    try {/*from  w  w  w . j av a  2 s.  com*/
        buffer.writeShort(request.getStreamId());
        buffer.writeShort(stat);
        buffer.writeInt(dlen);
        getBytes(buffer);
    } catch (Error | RuntimeException t) {
        promise.setFailure(t);
        buffer.release();
        return;
    } finally {
        ReferenceCountUtil.release(this);
    }
    ctx.write(buffer, promise);
}

From source file:org.dcache.xrootd.protocol.messages.AsyncResponse.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, final ChannelPromise promise) {
    try {/*ww w . j a v  a  2s. co m*/
        int dlen = getDataLength();
        ByteBuf header = ctx.alloc().buffer(8 + dlen);
        try {
            header.writeShort(0);
            header.writeShort(kXR_attn);
            header.writeInt(dlen);
            header.writeInt(kXR_asynresp);
            header.writeInt(0);
        } catch (Error | RuntimeException t) {
            promise.setFailure(t);
            header.release();
            return;
        }
        ctx.write(header).addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (!future.isSuccess()) {
                    promise.tryFailure(future.cause());
                }
            }
        });

        ChannelPromise channelPromise = ctx.newPromise();
        channelPromise.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                if (future.isSuccess()) {
                    promise.trySuccess();
                } else {
                    promise.tryFailure(future.cause());
                }
            }
        });
        ReferenceCountUtil.retain(response).writeTo(ctx, channelPromise);
    } finally {
        release();
    }
}

From source file:org.dcache.xrootd.tpc.protocol.messages.AbstractXrootdOutboundRequest.java

License:Open Source License

public void writeTo(ChannelHandlerContext ctx, ChannelPromise promise) {
    ByteBuf buffer = ctx.alloc().buffer(4 + getParamsLen());
    try {//from  w  w w .j a  va  2s  .c o m
        writeToBuffer(buffer);
    } catch (Error | RuntimeException t) {
        promise.setFailure(t);
        buffer.release();
        return;
    }
    ctx.write(buffer, promise);
}

From source file:org.dcache.xrootd.tpc.protocol.messages.OutboundHandshakeRequest.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, ChannelPromise promise) {
    ByteBuf buffer = ctx.alloc().buffer(XrootdProtocol.CLIENT_HANDSHAKE_LEN);
    try {//from ww  w . j av  a2s  .c o m
        buffer.writeBytes(XrootdProtocol.HANDSHAKE_REQUEST);
    } catch (Error | RuntimeException t) {
        promise.setFailure(t);
        buffer.release();
        return;
    }

    ctx.write(buffer, promise);
}

From source file:org.dcache.xrootd.tpc.protocol.messages.OutboundProtocolRequest.java

License:Open Source License

@Override
public void writeTo(ChannelHandlerContext ctx, ChannelPromise promise) {
    ByteBuf buffer = ctx.alloc().buffer(24);
    try {/* w  w w.java  2  s  . c  o  m*/
        buffer.writeShort(streamId);
        buffer.writeShort(kXR_protocol);
        buffer.writeInt(version);
        buffer.writeBytes(RESERVED);
        buffer.writeByte(kXR_secreqs);
        buffer.writeInt(0);
    } catch (Error | RuntimeException t) {
        promise.setFailure(t);
        buffer.release();
        return;
    }

    ctx.write(buffer, promise);
}