Java Code Examples for org.jboss.netty.channel.ChannelFuture#isSuccess()

The following examples show how to use org.jboss.netty.channel.ChannelFuture#isSuccess() . 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 File: HlsStreamsHandler.java    From feeyo-hlsserver with Apache License 2.0 6 votes vote down vote up
@Override
public void execute(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
	
	VelocityBuilder velocityBuilder = new VelocityBuilder();
	Map<String,Object> model = new HashMap<String, Object>();
	
	model.put("streams", HlsLiveStreamMagr.INSTANCE().getAllLiveStream()); 
	
	String htmlText = velocityBuilder.generate("streams.vm", "UTF8", model);
	
	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, Charset.defaultCharset());// CharsetUtil.UTF_8);
	response.setContent(buffer);

	ChannelFuture channelFuture = ctx.getChannel().write(response);
	if (channelFuture.isSuccess()) {
		channelFuture.getChannel().close();
	}
	
}
 
Example 2
Source File: Connection.java    From nfs-client-java with 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 3
Source File: RPCService.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
@Override
public void operationComplete(ChannelFuture cf) throws Exception {
    if (!cf.isSuccess()) {
        synchronized (connections) {
            NodeConnection c = connections.remove(node.getNodeId());
            if (c != null) c.nuke();
            cf.getChannel().close();
        }
        
        String message = "[unknown error]";
        if (cf.isCancelled()) message = "Timed out on connect";
        if (cf.getCause() != null) message = cf.getCause().getMessage();
        logger.debug("[{}->{}] Could not connect to RPC " +
                     "node: {}", 
                     new Object[]{syncManager.getLocalNodeId(), 
                                  node.getNodeId(), 
                                  message});
    } else {
        logger.trace("[{}->{}] Channel future successful", 
                     syncManager.getLocalNodeId(), 
                     node.getNodeId());
    }
}
 
Example 4
Source File: WelcomeHandler.java    From feeyo-hlsserver with 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 5
Source File: ChannelWriteCompleteListenableFuture.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
    if (future.isSuccess()) {
        this.setResult(result);
    } else {
        this.setFailure(future.getCause());
    }
}
 
Example 6
Source File: HttpUtil.java    From feeyo-hlsserver with 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 7
Source File: WriteFailFutureListener.java    From pinpoint with 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 8
Source File: InvokeFuture.java    From voyage with 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 9
Source File: ShuffleHandler.java    From tez with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
  if (future.isSuccess()) {
    shuffleOutputsOK.incr();
  } else {
    shuffleOutputsFailed.incr();
  }
  shuffleConnections.decr();
}
 
Example 10
Source File: NettyTcpClientTransport.java    From msgpack-rpc-java with Apache License 2.0 5 votes vote down vote up
public void operationComplete(ChannelFuture future) throws Exception {
    if (!future.isSuccess()) {
        onConnectFailed(future.getChannel(), future.getCause());
        return;
    }
    Channel c = future.getChannel();
    c.getCloseFuture().addListener(closeListener);
    onConnected(c);
}
 
Example 11
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void deleteFile(ClientBootstrap bootstrap, String host,
		int port, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new DeleteFileClientHandler(host, uri,
			filePath, userName, pwd);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 12
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void replaceFile(ClientBootstrap bootstrap, String host,
		int port, File file, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new ReplaceFileClientHandler(host, uri,
			filePath, file, userName, pwd);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 13
Source File: FileClient.java    From netty-file-parent with Apache License 2.0 5 votes vote down vote up
private static void createThumbPicture(ClientBootstrap bootstrap,
		String host, int port, String filePath, String userName, String pwd) {
	URI uri = getUri(host, port);
	ChannelFuture future = bootstrap.connect(new InetSocketAddress(host,
			port));
	Channel channel = future.awaitUninterruptibly().getChannel();
	if (!future.isSuccess()) {
		future.getCause().printStackTrace();
		bootstrap.releaseExternalResources();
		return;
	}

	WrapFileClientHandler handler = new CreateThumbPictureClientHandler(
			host, uri, userName, pwd, filePath);
	HttpRequest request = handler.getRequest();
	HttpDataFactory factory = getHttpDataFactory();
	HttpPostRequestEncoder bodyRequestEncoder = handler
			.wrapRequestData(factory);
	channel.write(request);
	if (bodyRequestEncoder.isChunked()) {
		channel.write(bodyRequestEncoder).awaitUninterruptibly();
	}
	bodyRequestEncoder.cleanFiles();
	channel.getCloseFuture().awaitUninterruptibly();
	bootstrap.releaseExternalResources();
	factory.cleanAllHttpDatas();
}
 
Example 14
Source File: AbstractNSQClient.java    From TrendrrNSQClient with MIT License 5 votes vote down vote up
/**
 * Creates a new connection object.
 *
 * Handles connection and sending magic protocol
 * @param address
 * @param port
 * @return
 */
protected Connection createConnection(String address, int port) {

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

    // Wait until the connection attempt succeeds or fails.
    Channel channel = future.awaitUninterruptibly().getChannel();
    if (!future.isSuccess()) {
        log.error("Caught", future.getCause());
        return null;
    }
    log.info("Creating connection: " + address + " : " + port);
    Connection conn = new Connection(address, port, channel, this);
    conn.setMessagesPerBatch(this.messagesPerBatch);

    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    buf.writeBytes(MAGIC_PROTOCOL_VERSION);
    channel.write(buf);

    //indentify
    try {
        String identJson = "{" +
                "\"short_id\":\"" + InetAddress.getLocalHost().getHostName() + "\"" +
                "," +
                "\"long_id\":\"" + InetAddress.getLocalHost().getCanonicalHostName() + "\"" +
                "}";
        NSQCommand ident = NSQCommand.instance("IDENTIFY", identJson.getBytes());
        conn.command(ident);

    } catch (UnknownHostException e) {
        log.error("Caught", e);
    }

    return conn;
}
 
Example 15
Source File: ShuffleHandler.java    From hadoop with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) throws Exception {
  if (future.isSuccess()) {
    shuffleOutputsOK.incr();
  } else {
    shuffleOutputsFailed.incr();
  }
  shuffleConnections.decr();
}
 
Example 16
Source File: NettyClient.java    From dubbo-2.6.5 with Apache License 2.0 4 votes vote down vote up
@Override
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try {
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);

        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // Close old channel
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    } finally {
        if (!isConnected()) {
            future.cancel();
        }
    }
}
 
Example 17
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 18
Source File: OspfInterfaceImpl.java    From onos with Apache License 2.0 4 votes vote down vote up
@Override
public void run() {
    if (channel != null && channel.isOpen() && channel.isConnected()) {
        if (interfaceType() == OspfInterfaceType.BROADCAST.value()) {
            if (interfaceTypeOldValue != interfaceType()) {
                try {
                    callDrElection(channel);
                } catch (Exception e) {
                    log.debug("Error while calling interfaceUp {}", e.getMessage());
                }
            }
        } else {
            if (interfaceTypeOldValue != interfaceType()) {
                interfaceTypeOldValue = interfaceType();
            }
        }
        HelloPacket hellopacket = new HelloPacket();
        //Headers
        hellopacket.setOspfVer(OspfUtil.OSPF_VERSION);
        hellopacket.setOspftype(OspfPacketType.HELLO.value());
        hellopacket.setOspfPacLength(0); //will be modified while encoding
        hellopacket.setRouterId(ospfArea.routerId());
        hellopacket.setAreaId(ospfArea.areaId());
        hellopacket.setChecksum(0); //will be modified while encoding
        hellopacket.setAuthType(OspfUtil.NOT_ASSIGNED);
        hellopacket.setAuthentication(OspfUtil.NOT_ASSIGNED);
        //Body
        hellopacket.setNetworkMask(ipNetworkMask());
        hellopacket.setOptions(ospfArea.options());
        hellopacket.setHelloInterval(helloIntervalTime());
        hellopacket.setRouterPriority(routerPriority());
        hellopacket.setRouterDeadInterval(routerDeadIntervalTime());
        hellopacket.setDr(dr());
        hellopacket.setBdr(bdr());

        Map<String, OspfNbr> listOfNeighbors = listOfNeighbors();
        Set<String> keys = listOfNeighbors.keySet();
        Iterator itr = keys.iterator();
        while (itr.hasNext()) {
            String nbrKey = (String) itr.next();
            OspfNbrImpl nbr = (OspfNbrImpl) listOfNeighbors.get(nbrKey);
            if (nbr.getState() != OspfNeighborState.DOWN) {
                hellopacket.addNeighbor(Ip4Address.valueOf(nbrKey));
            }
        }
        // build a hello Packet
        if (channel == null || !channel.isOpen() || !channel.isConnected()) {
            log.debug("Hello Packet not sent !!.. Channel Issue...");
            return;
        }

        hellopacket.setDestinationIp(OspfUtil.ALL_SPF_ROUTERS);
        byte[] messageToWrite = getMessage(hellopacket);
        ChannelFuture future = channel.write(messageToWrite);
        if (future.isSuccess()) {
            log.debug("Hello Packet successfully sent !!");
        } else {
            future.awaitUninterruptibly();
        }

    }
}
 
Example 19
Source File: NettyClient.java    From dubbox with Apache License 2.0 4 votes vote down vote up
protected void doConnect() throws Throwable {
    long start = System.currentTimeMillis();
    ChannelFuture future = bootstrap.connect(getConnectAddress());
    try{
        boolean ret = future.awaitUninterruptibly(getConnectTimeout(), TimeUnit.MILLISECONDS);
        
        if (ret && future.isSuccess()) {
            Channel newChannel = future.getChannel();
            newChannel.setInterestOps(Channel.OP_READ_WRITE);
            try {
                // 关闭旧的连接
                Channel oldChannel = NettyClient.this.channel; // copy reference
                if (oldChannel != null) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close old netty channel " + oldChannel + " on create new netty channel " + newChannel);
                        }
                        oldChannel.close();
                    } finally {
                        NettyChannel.removeChannelIfDisconnected(oldChannel);
                    }
                }
            } finally {
                if (NettyClient.this.isClosed()) {
                    try {
                        if (logger.isInfoEnabled()) {
                            logger.info("Close new netty channel " + newChannel + ", because the client closed.");
                        }
                        newChannel.close();
                    } finally {
                        NettyClient.this.channel = null;
                        NettyChannel.removeChannelIfDisconnected(newChannel);
                    }
                } else {
                    NettyClient.this.channel = newChannel;
                }
            }
        } else if (future.getCause() != null) {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + ", error message is:" + future.getCause().getMessage(), future.getCause());
        } else {
            throw new RemotingException(this, "client(url: " + getUrl() + ") failed to connect to server "
                    + getRemoteAddress() + " client-side timeout "
                    + getConnectTimeout() + "ms (elapsed: " + (System.currentTimeMillis() - start) + "ms) from netty client "
                    + NetUtils.getLocalHost() + " using dubbo version " + Version.getVersion());
        }
    }finally{
        if (! isConnected()) {
            future.cancel();
        }
    }
}
 
Example 20
Source File: HttpUtil.java    From feeyo-hlsserver with Apache License 2.0 4 votes vote down vote up
public static void sendNotModified(ChannelHandlerContext ctx, HttpResponse response) {
    ChannelFuture channelFuture = ctx.getChannel().write(response);
    if (channelFuture.isSuccess()) {
        channelFuture.getChannel().close();
    }
}