Java Code Examples for org.jboss.netty.channel.ChannelFuture

The following examples show how to use org.jboss.netty.channel.ChannelFuture. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: dubbo-2.6.5   Source File: NettyChannel.java    License: Apache License 2.0 6 votes vote down vote up
@Override
    public void send(Object message, boolean sent) throws RemotingException {
        super.send(message, sent);

        boolean success = true;
        int timeout = 0;
        try {
//            com.alibaba.dubbo.remoting.transport.AbstractPeer#received
            ChannelFuture future = channel.write(message);
            if (sent) {
                timeout = getUrl().getPositiveParameter(Constants.TIMEOUT_KEY, Constants.DEFAULT_TIMEOUT);
                success = future.await(timeout);
            }
            Throwable cause = future.getCause();
            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");
        }
    }
 
Example 2
Source Project: feeyo-hlsserver   Source File: WelcomeHandler.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) {

	VelocityBuilder velocityBuilder = new VelocityBuilder();
	String htmlText = velocityBuilder.generate("index.vm", "UTF8", null);	
	
	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK);
	response.headers().add(HttpHeaders.Names.CONTENT_LENGTH, htmlText.length());
	response.headers().set(HttpHeaders.Names.CONTENT_TYPE, "text/html; charset=UTF-8");
	
	ChannelBuffer buffer = ChannelBuffers.copiedBuffer(htmlText, CharsetUtil.UTF_8);
	response.setContent(buffer);

	ChannelFuture channelFuture = ctx.getChannel().write(response);
	if (channelFuture.isSuccess()) {
		channelFuture.getChannel().close();
	}
}
 
Example 3
Source Project: jstorm   Source File: NettyClient.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Avoid channel double close
 */
void closeChannel(final Channel channel) {
    synchronized (channelClosing) {
        if (closingChannel.contains(channel)) {
            LOG.info(channel.toString() + " has already been closed");
            return;
        }

        closingChannel.add(channel);
    }

    LOG.debug(channel.toString() + " begin to close");
    ChannelFuture closeFuture = channel.close();
    closeFuture.addListener(new ChannelFutureListener() {
        public void operationComplete(ChannelFuture future) throws Exception {

            synchronized (channelClosing) {
                closingChannel.remove(channel);
            }
            LOG.debug(channel.toString() + " closed.");
        }
    });
}
 
Example 4
Source Project: netty-file-parent   Source File: FileServerHandler.java    License: Apache License 2.0 6 votes vote down vote up
private void writeResponse(Channel channel) {
	ChannelBuffer buf = ChannelBuffers.copiedBuffer(
			this.responseContent.toString(), CharsetUtil.UTF_8);
	this.responseContent.setLength(0);

	boolean close = ("close".equalsIgnoreCase(this.request
			.getHeader("Connection")))
			|| ((this.request.getProtocolVersion()
					.equals(HttpVersion.HTTP_1_0)) && (!"keep-alive"
					.equalsIgnoreCase(this.request.getHeader("Connection"))));

	HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
			HttpResponseStatus.OK);
	response.setContent(buf);
	response.setHeader("Content-Type", "text/plain; charset=UTF-8");
	if (!close) {
		response.setHeader("Content-Length",
				String.valueOf(buf.readableBytes()));
	}
	ChannelFuture future = channel.write(response);
	if (close)
		future.addListener(ChannelFutureListener.CLOSE);
}
 
Example 5
Source Project: hadoop   Source File: TestShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate shuffle connection and input/output metrics.
 *
 * @throws Exception exception
 */
@Test (timeout = 10000)
public void testShuffleMetrics() throws Exception {
  MetricsSystem ms = new MetricsSystemImpl();
  ShuffleHandler sh = new ShuffleHandler(ms);
  ChannelFuture cf = make(stub(ChannelFuture.class).
      returning(true, false).from.isSuccess());

  sh.metrics.shuffleConnections.incr();
  sh.metrics.shuffleOutputBytes.incr(1*MiB);
  sh.metrics.shuffleConnections.incr();
  sh.metrics.shuffleOutputBytes.incr(2*MiB);

  checkShuffleMetrics(ms, 3*MiB, 0 , 0, 2);

  sh.metrics.operationComplete(cf);
  sh.metrics.operationComplete(cf);

  checkShuffleMetrics(ms, 3*MiB, 1, 1, 0);
}
 
Example 6
Source Project: hadoop   Source File: SimpleTcpClient.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  // Configure the client.
  ChannelFactory factory = new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
  ClientBootstrap bootstrap = new ClientBootstrap(factory);

  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(setPipelineFactory());

  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);

  // Start the connection attempt.
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

  if (oneShot) {
    // Wait until the connection is closed or the connection attempt fails.
    future.getChannel().getCloseFuture().awaitUninterruptibly();

    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
  }
}
 
Example 7
Source Project: big-c   Source File: SimpleTcpClient.java    License: Apache License 2.0 6 votes vote down vote up
public void run() {
  // Configure the client.
  ChannelFactory factory = new NioClientSocketChannelFactory(
      Executors.newCachedThreadPool(), Executors.newCachedThreadPool(), 1, 1);
  ClientBootstrap bootstrap = new ClientBootstrap(factory);

  // Set up the pipeline factory.
  bootstrap.setPipelineFactory(setPipelineFactory());

  bootstrap.setOption("tcpNoDelay", true);
  bootstrap.setOption("keepAlive", true);

  // Start the connection attempt.
  ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port));

  if (oneShot) {
    // Wait until the connection is closed or the connection attempt fails.
    future.getChannel().getCloseFuture().awaitUninterruptibly();

    // Shut down thread pools to exit.
    bootstrap.releaseExternalResources();
  }
}
 
Example 8
Source Project: dubbox   Source File: NettyChannel.java    License: Apache License 2.0 6 votes vote down vote up
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.getCause();
        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");
    }
}
 
Example 9
Source Project: nfs-client-java   Source File: Connection.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * This attempts to bind to privileged ports, starting with 1023 and working downwards, and returns when the first binding succeeds.
 * 
 * <p>
 * Some NFS servers apparently may require that some requests originate on
 * an Internet port below IPPORT_RESERVED (1024). This is generally not
 * used, though, as the client then has to run as a user authorized for
 * privileged, which is dangerous. It is also not generally needed.
 * </p>
 * 
 * @return
 *         <ul>
 *         <li><code>true</code> if the binding succeeds,</li>
 *         <li><code>false</code> otherwise.</li>
 *         </ul>
 * @throws RpcException If an exception occurs, or if no binding succeeds.
 */
private Channel bindToPrivilegedPort() throws RpcException {
    System.out.println("Attempting to use privileged port.");
    for (int port = 1023; port > 0; --port) {
        try {
            ChannelPipeline pipeline = _clientBootstrap.getPipelineFactory().getPipeline();
            Channel channel = _clientBootstrap.getFactory().newChannel(pipeline);
            channel.getConfig().setOptions(_clientBootstrap.getOptions());
            ChannelFuture bindFuture = channel.bind(new InetSocketAddress(port)).awaitUninterruptibly();
            if (bindFuture.isSuccess()) {
                System.out.println("Success! Bound to port " + port);
                return bindFuture.getChannel();
            }
        } catch (Exception e) {
            String msg = String.format("rpc request bind error for address: %s", 
                    getRemoteAddress());
            throw new RpcException(RpcStatus.NETWORK_ERROR, msg, e);
        }
    }

    throw new RpcException(RpcStatus.LOCAL_BINDING_ERROR, String.format("Cannot bind a port < 1024: %s", getRemoteAddress()));
}
 
Example 10
protected boolean connect(String hostname, int port) {
    ready = false;
    if (channel == null || !channel.isConnected()) {
        SocketAddress sa =
                new InetSocketAddress(hostname, port);
        ChannelFuture future = clientBootstrap.connect(sa);
        future.awaitUninterruptibly();
        if (!future.isSuccess()) {
            logger.error("Could not connect to " + hostname + 
                         ":" + port, future.getCause());
            return false;
        }
        channel = future.getChannel();
    }
    while (!ready && channel != null && channel.isConnected()) {
        try {
            Thread.sleep(10);
        } catch (InterruptedException e) { }
    }
    if (!ready || channel == null || !channel.isConnected()) {
        logger.warn("Timed out connecting to {}:{}", hostname, port);
        return false;
    }
    logger.debug("Connected to {}:{}", hostname, port);
    return true;
}
 
Example 11
Source Project: dubbox   Source File: NettyChannel.java    License: Apache License 2.0 6 votes vote down vote up
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.getCause();
        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");
    }
}
 
Example 12
Source Project: tez   Source File: TestShuffleHandler.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Validate shuffle connection and input/output metrics.
 *
 * @throws Exception exception
 */
@Test (timeout = 10000)
public void testShuffleMetrics() throws Exception {
  MetricsSystem ms = new MetricsSystemImpl();
  ShuffleHandler sh = new ShuffleHandler(ms);
  ChannelFuture cf = mock(ChannelFuture.class);
  when(cf.isSuccess()).thenReturn(true, false);

  sh.metrics.shuffleConnections.incr();
  sh.metrics.shuffleOutputBytes.incr(1*MiB);
  sh.metrics.shuffleConnections.incr();
  sh.metrics.shuffleOutputBytes.incr(2*MiB);

  checkShuffleMetrics(ms, 3*MiB, 0 , 0, 2);

  sh.metrics.operationComplete(cf);
  sh.metrics.operationComplete(cf);

  checkShuffleMetrics(ms, 3*MiB, 1, 1, 0);
}
 
Example 13
Source Project: pinpoint   Source File: DefaultPinpointClientHandler.java    License: Apache License 2.0 5 votes vote down vote up
private void sendClosedPacket(Channel channel) {
    if (!channel.isConnected()) {
        logger.debug("{} sendClosedPacket() failed. Error:channel already closed.", objectUniqName);
        return;
    }

    logger.debug("{} sendClosedPacket() started.", objectUniqName);

    ClientClosePacket clientClosePacket = new ClientClosePacket();
    ChannelFuture write = write0(clientClosePacket, sendClosePacketFailFutureListener);
    write.awaitUninterruptibly(3000, TimeUnit.MILLISECONDS);
}
 
Example 14
Source Project: Flink-CEPplus   Source File: NetworkFailureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example 15
Source Project: flink   Source File: NetworkFailureHandler.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void channelOpen(ChannelHandlerContext context, ChannelStateEvent event) throws Exception {
	// Suspend incoming traffic until connected to the remote host.
	final Channel sourceChannel = event.getChannel();
	sourceChannel.setReadable(false);

	boolean isBlocked = blocked.get();
	LOG.debug("Attempt to open proxy channel from [{}] to [{}:{}] in state [blocked = {}]",
		sourceChannel.getLocalAddress(),
		remoteHost,
		remotePort,
		isBlocked);

	if (isBlocked) {
		sourceChannel.close();
		return;
	}

	// Start the connection attempt.
	ClientBootstrap targetConnectionBootstrap = new ClientBootstrap(channelFactory);
	targetConnectionBootstrap.getPipeline().addLast(TARGET_CHANNEL_HANDLER_NAME, new TargetChannelHandler(event.getChannel(), blocked));
	ChannelFuture connectFuture = targetConnectionBootstrap.connect(new InetSocketAddress(remoteHost, remotePort));
	sourceToTargetChannels.put(sourceChannel, connectFuture.getChannel());

	connectFuture.addListener(future -> {
		if (future.isSuccess()) {
			// Connection attempt succeeded:
			// Begin to accept incoming traffic.
			sourceChannel.setReadable(true);
		} else {
			// Close the connection if the connection attempt has failed.
			sourceChannel.close();
		}
	});
}
 
Example 16
Source Project: canal-1.1.3   Source File: ChannelFutureAggregator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) {
    // profiling after I/O operation
    if (future != null && future.getCause() != null) {
        result.channelError = future.getCause();
    }
    profiler().profiling(result);
}
 
Example 17
Source Project: elasticsearch-helper   Source File: HttpInvoker.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Override
public <Request extends ActionRequest, Response extends ActionResponse, RequestBuilder extends ActionRequestBuilder<Request, Response, RequestBuilder>>
        void doExecute(Action<Request, Response, RequestBuilder> action, Request request, ActionListener<Response> listener) {
    HttpElasticsearchClient.ActionEntry entry = actionMap.get(action.name());
    if (entry == null) {
        throw new IllegalStateException("no action entry for " + action.name());
    }
    HttpAction<Request, Response> httpAction = entry.httpAction;
    if (httpAction == null) {
        throw new IllegalStateException("failed to find action [" + action + "] to execute");
    }
    HttpInvocationContext<Request, Response> httpInvocationContext = new HttpInvocationContext(httpAction, listener, new LinkedList<>(), request);
    try {
        httpInvocationContext.httpRequest = httpAction.createHttpRequest(this.url, request);
    } catch (IOException e) {
        logger.error(e.getMessage(), e);
    }
    ChannelFuture future = bootstrap.connect(new InetSocketAddress(url.getHost(), url.getPort()));
    future.awaitUninterruptibly();
    if (!future.isSuccess()) {
        bootstrap.releaseExternalResources();
        logger.error("can't connect to {}", url);
    } else {
        Channel channel = future.getChannel();
        httpInvocationContext.setChannel(channel);
        contexts.put(channel, httpInvocationContext);
        channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
        httpAction.execute(httpInvocationContext, listener);
    }
}
 
Example 18
Source Project: feeyo-hlsserver   Source File: HttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void sendError(ChannelHandlerContext ctx, HttpResponseStatus code) throws InterruptedException {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, code);
    ChannelFuture channelFuture = ctx.getChannel().write(response).sync();
    if (channelFuture.isSuccess()) {
        channelFuture.getChannel().close();
    }
}
 
Example 19
Source Project: feeyo-hlsserver   Source File: HttpUtil.java    License: Apache License 2.0 5 votes vote down vote up
public static void sendNotModified(ChannelHandlerContext ctx) {
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.NOT_MODIFIED);
    ChannelFuture channelFuture = ctx.getChannel().write(response);
    if (channelFuture.isSuccess()) {
        channelFuture.getChannel().close();
    }
}
 
Example 20
Source Project: voyage   Source File: InvokeFuture.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 发送请求
 */
public void send() {
	ChannelFuture writeFuture = channel.write(request);
	//阻塞等待,若超时则返回已完成和失败
	boolean ret = writeFuture.awaitUninterruptibly(1000, TimeUnit.MILLISECONDS);
	if (ret && writeFuture.isSuccess()) {
		return;
	} else if(writeFuture.getCause() != null) {
		invokeMap.remove(request.getRequestID());
		throw new RpcException(writeFuture.getCause());
	} else {
		invokeMap.remove(request.getRequestID());
		throw new RpcException("sendRequest error");
	}
}
 
Example 21
Source Project: voyage   Source File: NettyRpcConnection.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 尝试连接
 */
public void connect() {
       ChannelFuture future = bootstrap.connect(inetAddr);
       try{
           boolean ret = future.awaitUninterruptibly(Constants.TIMEOUT_CONNECTION_MILLSECOND, TimeUnit.MILLISECONDS);
           if (ret && future.isSuccess()) {
               Channel newChannel = future.getChannel();
               newChannel.setInterestOps(Channel.OP_READ_WRITE);
               try {
                   // 关闭旧的连接
                   Channel oldChannel = NettyRpcConnection.this.channel;
                   if (oldChannel != null) {
                       logger.info("Close old netty channel {} on create new netty channel {}", oldChannel, newChannel);
                       oldChannel.close();
                   }
               } finally {
                   if (!isConnected()) {
                       try {
                           logger.info("Close new netty channel {}, because the client closed.", newChannel);
                           newChannel.close();
                       } finally {
                       	NettyRpcConnection.this.channel = null;
                       }
                   } else {
                   	NettyRpcConnection.this.channel = newChannel;
                   }
               }
           } else if (null != future.getCause()) {
           	logger.error("connect fail", future.getCause());
           	throw new RuntimeException("connect error", future.getCause());
           } else {
           	logger.error("connect fail,connstr: "+this.getConnStr());
           	throw new RuntimeException("connect error");
           }
       }finally{
           if (! isConnected()) {
               future.cancel();
           }
       }
}
 
Example 22
Source Project: Elasticsearch   Source File: NettyTransport.java    License: Apache License 2.0 5 votes vote down vote up
protected void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
    if (!lifecycle.started()) {
        // ignore
        return;
    }
    if (isCloseConnectionException(e.getCause())) {
        logger.trace("close connection exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
        // close the channel, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (isConnectException(e.getCause())) {
        logger.trace("connect exception caught on transport layer [{}]", e.getCause(), ctx.getChannel());
        // close the channel as safe measure, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (e.getCause() instanceof CancelledKeyException) {
        logger.trace("cancelled key exception caught on transport layer [{}], disconnecting from relevant node", e.getCause(), ctx.getChannel());
        // close the channel as safe measure, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    } else if (e.getCause() instanceof SizeHeaderFrameDecoder.HttpOnTransportException) {
        // in case we are able to return data, serialize the exception content and sent it back to the client
        if (ctx.getChannel().isOpen()) {
            ChannelBuffer buffer = ChannelBuffers.wrappedBuffer(e.getCause().getMessage().getBytes(Charsets.UTF_8));
            ChannelFuture channelFuture = ctx.getChannel().write(buffer);
            channelFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    future.getChannel().close();
                }
            });
        }
    } else {
        logger.warn("exception caught on transport layer [{}], closing connection", e.getCause(), ctx.getChannel());
        // close the channel, which will cause a node to be disconnected if relevant
        ctx.getChannel().close();
        disconnectFromNodeChannel(ctx.getChannel(), e.getCause());
    }
}
 
Example 23
Source Project: Elasticsearch   Source File: NettyTransport.java    License: Apache License 2.0 5 votes vote down vote up
public synchronized void close() {
    List<ChannelFuture> futures = new ArrayList<>();
    for (Channel channel : allChannels) {
        try {
            if (channel != null && channel.isOpen()) {
                futures.add(channel.close());
            }
        } catch (Exception e) {
            //ignore
        }
    }
    for (ChannelFuture future : futures) {
        future.awaitUninterruptibly();
    }
}
 
Example 24
Source Project: Elasticsearch   Source File: NettyTransportChannel.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void sendResponse(TransportResponse response, TransportResponseOptions options) throws IOException {
    if (transport.compress) {
        options = TransportResponseOptions.builder(options).withCompress(transport.compress).build();
    }

    byte status = 0;
    status = TransportStatus.setResponse(status);

    ReleasableBytesStreamOutput bStream = new ReleasableBytesStreamOutput(transport.bigArrays);
    boolean addedReleaseListener = false;
    try {
        bStream.skip(NettyHeader.HEADER_SIZE);
        StreamOutput stream = bStream;
        if (options.compress()) {
            status = TransportStatus.setCompress(status);
            stream = CompressorFactory.defaultCompressor().streamOutput(stream);
        }
        stream.setVersion(version);
        response.writeTo(stream);
        stream.close();

        ReleasablePagedBytesReference bytes = bStream.bytes();
        ChannelBuffer buffer = bytes.toChannelBuffer();
        NettyHeader.writeHeader(buffer, requestId, status, version);
        ChannelFuture future = channel.write(buffer);
        ReleaseChannelFutureListener listener = new ReleaseChannelFutureListener(bytes);
        future.addListener(listener);
        addedReleaseListener = true;
        transportServiceAdapter.onResponseSent(requestId, action, response, options);
    } finally {
        if (!addedReleaseListener) {
            Releasables.close(bStream.bytes());
        }
    }
}
 
Example 25
Source Project: netty-file-parent   Source File: FileClient.java    License: Apache License 2.0 5 votes vote down vote up
private static void uploadFile(ClientBootstrap bootstrap, String host,
		int port, File file, String fileName, String thumbMark,
		String userName, String pwd) {
	//1.构建uri对象
	URI uri = getUri(host, port);
	//2.连接netty服务端
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	//3.异步获取Channel对象
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}
	//4.初始化文件上传句柄对象
	WrapFileClientHandler handler = new UploadFileClientHandler(host, uri,
			file, fileName, thumbMark, userName, pwd);
	//5.获取Request对象
	HttpRequest request = handler.getRequest();
	//6.获取Http数据处理工厂
	HttpDataFactory factory = getHttpDataFactory();
	//7.进行数据的包装处理,主要是进行上传文件所需要的参数的设置,此时调用的句柄是具体的UploadFileClientHandler对象
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	//8.把request写到管道中,传输给服务端
	channel.write(request);
	//9.做一些关闭资源的动作
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();

	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 26
Source Project: tez   Source File: ShuffleHandler.java    License: Apache License 2.0 5 votes vote down vote up
protected ChannelFuture sendMapOutput(ChannelHandlerContext ctx, Channel ch,
    String user, String mapId, int reduce, MapOutputInfo mapOutputInfo)
    throws IOException {
  final TezIndexRecord info = mapOutputInfo.indexRecord;
  final ShuffleHeader header =
    new ShuffleHeader(mapId, info.getPartLength(), info.getRawLength(), reduce);
  final DataOutputBuffer dob = new DataOutputBuffer();
  header.write(dob);
  ch.write(wrappedBuffer(dob.getData(), 0, dob.getLength()));
  final File spillfile =
      new File(mapOutputInfo.mapOutputFileName.toString());
  RandomAccessFile spill;
  try {
    spill = SecureIOUtils.openForRandomRead(spillfile, "r", user, null);
  } catch (FileNotFoundException e) {
    LOG.info(spillfile + " not found");
    return null;
  }
  ChannelFuture writeFuture;
  final DefaultFileRegion partition =
      new DefaultFileRegion(spill.getChannel(), info.getStartOffset(), info.getPartLength());
  writeFuture = ch.write(partition);
  writeFuture.addListener(new ChannelFutureListener() {
    // TODO error handling; distinguish IO/connection failures,
    //      attribute to appropriate spill output
    @Override
    public void operationComplete(ChannelFuture future) {
      partition.releaseExternalResources();
    }
  });
  return writeFuture;
}
 
Example 27
Source Project: canal   Source File: ChannelFutureAggregator.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) {
    // profiling after I/O operation
    if (future != null && future.getCause() != null) {
        result.channelError = future.getCause();
    }
    profiler().profiling(result);
}
 
Example 28
Source Project: pinpoint   Source File: WriteFailFutureListener.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
        if (logger.isWarnEnabled()) {
            final Throwable cause = future.getCause();
            logger.warn("{} channel:{} Caused:{}", failMessage, future.getChannel(), cause.getMessage(), cause);
        }
    } else {
        if (successMessage != null) {
            if (logger.isDebugEnabled()) {
                logger.debug("{} channel:{}", successMessage, future.getChannel());
            }
        }
    }
}
 
Example 29
Source Project: phoenix-omid   Source File: TSOClientRaw.java    License: Apache License 2.0 5 votes vote down vote up
public TSOClientRaw(String host, int port) throws InterruptedException, ExecutionException {
    // Start client with Nb of active threads = 3 as maximum.
    ChannelFactory factory = new NioClientSocketChannelFactory(
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-boss-%d").build()),
            Executors.newCachedThreadPool(
                    new ThreadFactoryBuilder().setNameFormat("tsoclient-worker-%d").build()), 3);
    // Create the bootstrap
    ClientBootstrap bootstrap = new ClientBootstrap(factory);

    InetSocketAddress addr = new InetSocketAddress(host, port);

    ChannelPipeline pipeline = bootstrap.getPipeline();
    pipeline.addLast("lengthbaseddecoder",
            new LengthFieldBasedFrameDecoder(8 * 1024, 0, 4, 0, 4));
    pipeline.addLast("lengthprepender", new LengthFieldPrepender(4));
    pipeline.addLast("protobufdecoder",
            new ProtobufDecoder(TSOProto.Response.getDefaultInstance()));
    pipeline.addLast("protobufencoder", new ProtobufEncoder());

    Handler handler = new Handler();
    pipeline.addLast("handler", handler);

    bootstrap.setOption("tcpNoDelay", true);
    bootstrap.setOption("keepAlive", true);
    bootstrap.setOption("reuseAddress", true);
    bootstrap.setOption("connectTimeoutMillis", 100);

    ChannelFuture channelFuture = bootstrap.connect(addr).await();
    channel = channelFuture.getChannel();
}
 
Example 30
Source Project: pinpoint   Source File: DefaultPinpointServer.java    License: Apache License 2.0 5 votes vote down vote up
public ChannelFuture sendClosePacket() {
    logger.info("{} sendClosePacket() started.", objectUniqName);
    
    SocketStateChangeResult stateChangeResult = state.toBeingClose();
    if (stateChangeResult.isChange()) {
        ChannelFuture writeFuture = write0(ServerClosePacket.DEFAULT_SERVER_CLOSE_PACKET, serverCloseWriteListener);
        logger.info("{} sendClosePacket() completed.", objectUniqName);
        return writeFuture;
    } else {
        logger.info("{} sendClosePacket() failed. Error:{}.", objectUniqName, stateChangeResult);
        return null;
    }
}