List of usage examples for io.netty.channel ChannelFuture cause
Throwable cause();
From source file:poke.server.worker.comm.CommHandler.java
License:Apache License
/** * messages pass through this method. We use a blackbox design as much as /*from w w w. j a va2 s.c o m*/ * possible to ensure we can replace the underlining communication without * affecting behavior. * * @param msg * @return * @throws InterruptedException */ public boolean send(GeneratedMessage msg, Channel ch) throws InterruptedException { // TODO a queue is needed to prevent overloading of the socket // connection. For the demonstration, we don't need it ChannelFuture cf = ch.writeAndFlush((Request) msg); cf.awaitUninterruptibly(); logger.info(" " + cf.cause()); if (cf.isDone() && !cf.isSuccess()) { logger.error("failed to poke!"); return false; } return true; }
From source file:proxy.mock.client.HttpClientBatch.java
License:Apache License
public void sendRequect() throws InterruptedException { //??//w ww.j ava 2 s . com // Prepare the HTTP request. String msg = new Gson().toJson(GenerateRespObject.getRequest()); final FullHttpRequest request = HttpUitls.createHttpRequest(uri.getRawPath(), msg); // Make the connection attempt. Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpClientHandler(request)); } }); b.connect(host, port).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { TokenMgr.getInstance().returnToken(); logger.warn(" connect failed " + future.cause().getMessage()); future.channel().close(); } else { future.channel().writeAndFlush(request); } } }); }
From source file:proxy.server.HttpBackendHandler.java
License:Apache License
@Override public void channelRead0(ChannelHandlerContext ctx, HttpObject msg) { if (msg instanceof HttpResponse) { //TODO /* w w w. j av a 2 s.c o m*/ } if (msg instanceof HttpContent) { HttpContent httpContent = (HttpContent) msg; buf.append(httpContent.content().toString(CharsetUtil.UTF_8)); if (msg instanceof LastHttpContent) { //TODO ?buf String content = buf.toString(); FullHttpResponse response = HttpUitls.createHttpResponse(HttpResponseStatus.OK, content); //? frontCtx.writeAndFlush(response).addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { String error = "write reponse to frontend failed." + future.cause().getMessage(); logger.warn(error); } frontCtx.close();//? } }); ctx.close();//? } } }
From source file:proxy.server.HttpBackendMgr.java
License:Apache License
public void forwardRequect(final ChannelHandlerContext frontCtx, TaskRequest request2) throws InterruptedException { //??//from w w w .ja va 2s . c o m // Prepare the HTTP request. String content = new Gson().toJson(request2); final FullHttpRequest request = HttpUitls.createHttpRequest(path, content); // Make the connection attempt. Bootstrap b = new Bootstrap(); b.group(group).channel(NioSocketChannel.class).handler(new ChannelInitializer<SocketChannel>() { @Override public void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); p.addLast(new HttpClientCodec()); p.addLast(new HttpContentDecompressor()); p.addLast(new HttpBackendHandler(frontCtx, request)); } }); b.connect(host, port).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { future.channel().close(); String error = "connect backend failed " + future.cause().getMessage(); logger.warn(error); FullHttpResponse response = HttpUitls.createHttpResponse(HttpResponseStatus.NOT_FOUND, error); frontCtx.writeAndFlush(response); } else { future.channel().writeAndFlush(request); } } }); }
From source file:pub.vrtech.monkey.transport.netty.NettyChannel.java
License:Apache License
/*** * ?????//from w ww .j a v a 2 s . c o m * @param message ??? * @param sent ???? */ public void send(Object message, boolean sent) throws RemotingException { super.send(message, sent); boolean success = true; int timeout = 0; try { ChannelFuture future = channel.write(message); if (sent) { timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT); success = future.await(timeout); } Throwable cause = future.cause(); if (cause != null) { throw cause; } } catch (Throwable e) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + ", cause: " + e.getMessage(), e); } if (!success) { throw new RemotingException(this, "Failed to send message " + message + " to " + getRemoteAddress() + "in timeout(" + timeout + "ms) limit"); } }
From source file:qunar.tc.qmq.netty.client.NettyClient.java
License:Apache License
public void sendAsync(String brokerAddr, Datagram request, long responseTimeout, ResponseFuture.Callback callback) throws ClientSendException { final Channel channel = getOrCreateChannel(brokerAddr); final ResponseFuture responseFuture = clientHandler.newResponse(channel, responseTimeout, callback); request.getHeader().setOpaque(responseFuture.getOpaque()); try {/*w w w .ja v a 2s . c om*/ channel.writeAndFlush(request).addListener(new ChannelFutureListener() { @Override public void operationComplete(ChannelFuture future) { if (future.isSuccess()) { responseFuture.setSendOk(true); return; } clientHandler.removeResponse(channel, responseFuture); responseFuture.completeBySendFail(future.cause()); LOGGER.error("send request to broker failed.", future.cause()); try { responseFuture.executeCallbackOnlyOnce(); } catch (Throwable e) { LOGGER.error("execute callback when send error exception", e); } } }); } catch (Exception e) { clientHandler.removeResponse(channel, responseFuture); responseFuture.completeBySendFail(e); LOGGER.warn("send request fail. brokerAddr={}", brokerAddr); throw new ClientSendException(SendErrorCode.WRITE_CHANNEL_FAIL, RemoteHelper.parseChannelRemoteAddress(channel), e); } }
From source file:qunar.tc.qmq.netty.client.NettyConnectManageHandler.java
License:Apache License
Channel getOrCreateChannel(final String remoteAddr) throws ClientSendException { if (Strings.isNullOrEmpty(remoteAddr)) { throw new ClientSendException(ClientSendException.SendErrorCode.EMPTY_ADDRESS); }/* ww w . jav a 2s. c o m*/ ChannelWrapper cw = channelTables.get(remoteAddr); if (cw != null && cw.isOK()) { return cw.getChannel(); } if (!tryLockChannelTable()) { throw new ClientSendException(ClientSendException.SendErrorCode.CREATE_CHANNEL_FAIL, remoteAddr); } try { boolean needCreateChannel = true; cw = channelTables.get(remoteAddr); if (cw != null) { if (cw.isOK()) { return cw.getChannel(); } else if (!cw.getChannelFuture().isDone()) { needCreateChannel = false; } else { channelTables.remove(remoteAddr); } } if (needCreateChannel) { ChannelFuture cf = bootstrap.connect(RemoteHelper.string2SocketAddress(remoteAddr)); LOGGER.debug("begin to connect remote host: {}", remoteAddr); cw = new ChannelWrapper(cf); channelTables.put(remoteAddr, cw); } } catch (Exception e) { LOGGER.error("create channel exception. remoteAddr={}", remoteAddr, e); } finally { channelLock.unlock(); } if (cw != null) { ChannelFuture cf = cw.getChannelFuture(); if (cf.awaitUninterruptibly(connectTimeout)) { if (cw.isOK()) { LOGGER.debug("connect remote host success: {}", remoteAddr); return cw.getChannel(); } else { if (connectFailLogLimit.tryAcquire()) { LOGGER.warn("connect remote host fail: {}. {}", remoteAddr, cf.toString(), cf.cause()); } } } else { if (connectFailLogLimit.tryAcquire()) { LOGGER.warn("connect remote host timeout: {}. {}", remoteAddr, cf.toString()); } } } throw new ClientSendException(ClientSendException.SendErrorCode.CREATE_CHANNEL_FAIL, remoteAddr); }
From source file:ratpack.http.client.internal.RequestActionSupport.java
License:Apache License
public void execute(final Fulfiller<? super T> fulfiller) throws Exception { final AtomicBoolean redirecting = new AtomicBoolean(); final Bootstrap b = new Bootstrap(); b.group(this.execution.getEventLoop()).channel(ChannelImplDetector.getSocketChannelImpl()) .handler(new ChannelInitializer<SocketChannel>() { @Override// ww w.j a va 2s. c o m protected void initChannel(SocketChannel ch) throws Exception { ChannelPipeline p = ch.pipeline(); if (finalUseSsl) { SSLEngine engine = SSLContext.getDefault().createSSLEngine(); engine.setUseClientMode(true); p.addLast("ssl", new SslHandler(engine)); } p.addLast("codec", new HttpClientCodec()); p.addLast("readTimeout", new ReadTimeoutHandler(requestParams.readTimeoutNanos, TimeUnit.NANOSECONDS)); p.addLast("redirectHandler", new SimpleChannelInboundHandler<HttpObject>(false) { @Override protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception { if (msg instanceof HttpResponse) { final HttpResponse response = (HttpResponse) msg; final Headers headers = new NettyHeadersBackedHeaders(response.headers()); final Status status = new DefaultStatus(response.status()); int maxRedirects = requestSpecBacking.getMaxRedirects(); String locationValue = headers.get("Location"); //Check for redirect and location header if it is follow redirect if we have request forwarding left if (shouldRedirect(status) && maxRedirects > 0 && locationValue != null) { redirecting.compareAndSet(false, true); Action<? super RequestSpec> redirectRequestConfig = Action .join(requestConfigurer, s -> { if (status.getCode() == 301 || status.getCode() == 302) { s.method("GET"); } s.redirects(maxRedirects - 1); }); URI locationUrl; if (ABSOLUTE_PATTERN.matcher(locationValue).matches()) { locationUrl = new URI(locationValue); } else { locationUrl = new URI(uri.getScheme(), null, uri.getHost(), uri.getPort(), locationValue, null, null); } buildRedirectRequestAction(redirectRequestConfig, locationUrl) .execute(fulfiller); } else { p.remove(this); } } if (!redirecting.get()) { ctx.fireChannelRead(msg); } } }); addResponseHandlers(p, fulfiller); } @Override public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception { ctx.close(); error(fulfiller, cause); } }); ChannelFuture connectFuture = b.connect(host, port); connectFuture.addListener(f1 -> { if (connectFuture.isSuccess()) { String fullPath = getFullPath(uri); FullHttpRequest request = new DefaultFullHttpRequest(HttpVersion.HTTP_1_1, HttpMethod.valueOf(requestSpecBacking.getMethod()), fullPath, requestSpecBacking.getBody()); if (headers.get(HttpHeaderConstants.HOST) == null) { headers.set(HttpHeaderConstants.HOST, host); } headers.set(HttpHeaderConstants.CONNECTION, HttpHeaderValues.CLOSE); int contentLength = request.content().readableBytes(); if (contentLength > 0) { headers.set(HttpHeaderConstants.CONTENT_LENGTH, Integer.toString(contentLength, 10)); } HttpHeaders requestHeaders = request.headers(); for (String name : headers.getNames()) { requestHeaders.set(name, headers.getAll(name)); } ChannelFuture writeFuture = connectFuture.channel().writeAndFlush(request); writeFuture.addListener(f2 -> { if (!writeFuture.isSuccess()) { writeFuture.channel().close(); error(fulfiller, writeFuture.cause()); } }); } else { connectFuture.channel().close(); error(fulfiller, connectFuture.cause()); } }); }
From source file:reactor.io.net.impl.netty.http.NettyHttpChannel.java
License:Open Source License
@Override public void subscribe(final Subscriber<? super IN> subscriber) { // Handle the 'Expect: 100-continue' header if necessary. // TODO: Respond with 413 Request Entity Too Large // and discard the traffic or close the connection. // No need to notify the upstream handlers - just log. // If decoding a response, just throw an exception. if (is100ContinueExpected(nettyRequest)) { tcpStream.delegate().writeAndFlush(CONTINUE).addListener(new ChannelFutureListener() { @Override//w w w . ja v a 2s . c o m public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { subscriber.onError(future.cause()); } else { tcpStream.subscribe(subscriber); } } }); } else { tcpStream.subscribe(subscriber); } }