org.jboss.netty.channel.ChannelFuture Java Examples

The following examples show how to use org.jboss.netty.channel.ChannelFuture. 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: SimpleTcpClient.java    From hadoop with 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 #2
Source File: TestShuffleHandler.java    From tez with 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 #3
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 #4
Source File: NettyChannel.java    From dubbo-2.6.5 with 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 #5
Source File: NettyClient.java    From jstorm with 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 #6
Source File: NettyChannel.java    From dubbox with 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 #7
Source File: NettyChannel.java    From dubbox with 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 #8
Source File: SimpleTcpClient.java    From big-c with 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 #9
Source File: RemoteSyncManager.java    From floodlight_with_topoguard with Apache License 2.0 6 votes vote down vote up
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 #10
Source File: FileServerHandler.java    From netty-file-parent with 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 #11
Source File: TestShuffleHandler.java    From hadoop with 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 #12
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 #13
Source File: FileCloseListener.java    From tajo with Apache License 2.0 5 votes vote down vote up
@Override
public void operationComplete(ChannelFuture future) {
  if(future.isSuccess()){
    filePart.transferSuccessful();
  }
  filePart.releaseExternalResources();
}
 
Example #14
Source File: PinpointClientHandshaker.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private void handshake(HandshakeJob handshakeJob) {
    handshakeCount.incrementAndGet();
    
    Channel channel = handshakeJob.getChannel();
    ControlHandshakePacket packet = handshakeJob.getHandshakePacket();
    
    logger.info("{} do handshake({}/{}). channel:{}.", id, handshakeCount.get(), maxHandshakeCount, channel);
    final ChannelFuture future = channel.write(packet);

    future.addListener(handShakeFailFutureListener);
}
 
Example #15
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 #16
Source File: NettyClient.java    From migration-tool with Apache License 2.0 5 votes vote down vote up
@Override
public void sendRequest(final int requestId, final String message, final int timeout) throws Exception {
	final long beginTime = System.currentTimeMillis();
	final Client self = this;
	ChannelFuture writeFuture = cf.getChannel().write(message);
	writeFuture.addListener(new ChannelFutureListener() {
		public void operationComplete(ChannelFuture future) throws Exception {
			if (future.isSuccess()) {
				return;
			}
			String errorMsg = "";
			// write timeout
			if (System.currentTimeMillis() - beginTime >= timeout) {
				errorMsg = "write to send buffer consume too long time(" + (System.currentTimeMillis() - beginTime) + "),request id is:"
						+ requestId;
			}
			if (future.isCancelled()) {
				errorMsg = "Send request to " + cf.getChannel().toString() + " cancelled by user,request id is:" + requestId;
			}
			if (!future.isSuccess()) {
				if (cf.getChannel().isConnected()) {
					// maybe some exception,so close the channel
					cf.getChannel().close();
				} else {
					NettyClientFactory.getInstance().removeClient(self);
				}
				errorMsg = "Send request to " + cf.getChannel().toString() + " error" + future.getCause();
			}
			log.error(errorMsg);
			self.putResponse(requestId + "|error|" + errorMsg);
		}
	});
}
 
Example #17
Source File: HttpElasticsearchClient.java    From elasticsearch-helper with 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) {
    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);
        contextMap.put(channel, httpInvocationContext);
        channel.getConfig().setConnectTimeoutMillis(settings.getAsInt("http.client.timeout", 5000));
        httpAction.execute(httpInvocationContext, listener);
    }
}
 
Example #18
Source File: ProxyTest.java    From FlowSpaceFirewall with Apache License 2.0 5 votes vote down vote up
public void setupChannel() throws IOException{
	ChannelFuture future = createMock(org.jboss.netty.channel.ChannelFuture.class);
	ChannelPipeline pipeline = createMock(org.jboss.netty.channel.ChannelPipeline.class);
	ChannelHandlerContext context = createMock(org.jboss.netty.channel.ChannelHandlerContext.class);
	handler = EasyMock.createNiceMock(edu.iu.grnoc.flowspace_firewall.OFControllerChannelHandler.class);
	channel = EasyMock.createNiceMock(org.jboss.netty.channel.socket.SocketChannel.class);
	
	ChannelFuture otherFuture = createMock(org.jboss.netty.channel.ChannelFuture.class);
	expect(channel.getPipeline()).andReturn(pipeline).anyTimes();
	expect(pipeline.getContext("handler")).andReturn(context).anyTimes();
	expect(context.getHandler()).andReturn(handler).anyTimes();
	expect(channel.connect(EasyMock.isA(java.net.InetSocketAddress.class))).andReturn(future).anyTimes();
	expect(channel.write(EasyMock.isA(org.openflow.protocol.OFMessage.class))).andReturn(otherFuture).anyTimes();
	
	handler.setSwitch(EasyMock.isA(net.floodlightcontroller.core.IOFSwitch.class));
	EasyMock.expectLastCall().anyTimes();
	
	handler.setProxy(EasyMock.isA(edu.iu.grnoc.flowspace_firewall.Proxy.class));
	EasyMock.expectLastCall().anyTimes();
	
	handler.sendMessage(EasyMock.isA(org.openflow.protocol.OFMessage.class));
	EasyMock.expectLastCall().andAnswer(new IAnswer<Object>() {
	    public Object answer() {
	        //supply your mock implementation here...
	        messagesSentToController.add((OFMessage)EasyMock.getCurrentArguments()[0]);
	        //return the value to be returned by the method (null for void)
	        return null;
	    }
	}).anyTimes();
	
	
	EasyMock.replay(future);
	EasyMock.replay(pipeline);
	EasyMock.replay(context);
	//EasyMock.replay(handler);
	EasyMock.replay(otherFuture);
}
 
Example #19
Source File: NetworkFailureHandler.java    From flink with 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 #20
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private ChannelFuture write0(Object message, ChannelFutureListener futureListener) {
    if (futureListener == null) {
        throw new NullPointerException("futureListener");
    }
    ChannelFuture future = write0(message);
    future.addListener(futureListener);
    return future;
}
 
Example #21
Source File: HealthCheckManagerTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
private Channel createMockChannel(HealthCheckState state) {
    Channel mockChannel = mock(Channel.class);
    when(mockChannel.isConnected()).thenReturn(true);

    ChannelFuture mockChannelFuture = mock(ChannelFuture.class);
    when(mockChannel.write(PingPacket.PING_PACKET)).thenReturn(mockChannelFuture);
    when(mockChannel.write(PingSimplePacket.PING_PACKET)).thenReturn(mockChannelFuture);
    when(mockChannel.getCloseFuture()).thenReturn(mockChannelFuture);

    PinpointServer pinpointServer = mock(PinpointServer.class);
    when(pinpointServer.getHealthCheckState()).thenReturn(state);
    when(mockChannel.getAttachment()).thenReturn(pinpointServer);

    return mockChannel;
}
 
Example #22
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 #23
Source File: NettyService.java    From android-netty with Apache License 2.0 5 votes vote down vote up
/** 연결을 다시 맺어야 할 경우 connection 을 닫는다.
 */
void disconnectSessionIfItNeeds() {
	if(checkConnection() == true) {
		ChannelFuture future = mChannel.disconnect();
		future.awaitUninterruptibly();
	}
}
 
Example #24
Source File: DefaultPinpointClientHandler.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Override
public Future sendAsync(byte[] bytes) {
    ChannelFuture channelFuture = send0(bytes);
    final ChannelWriteCompleteListenableFuture future = new ChannelWriteCompleteListenableFuture(clientOption.getWriteTimeoutMillis());
    channelFuture.addListener(future);
    return future;
}
 
Example #25
Source File: TSOClient.java    From phoenix-omid with Apache License 2.0 5 votes vote down vote up
private void sendRequest(final StateMachine.Fsm fsm, RequestEvent request) {
    TSOProto.Request req = request.getRequest();

    if (req.hasTimestampRequest()) {
        timestampRequests.add(new RequestAndTimeout(request, newTimeout(new TimestampRequestTimeoutEvent())));
    } else if (req.hasCommitRequest()) {
        TSOProto.CommitRequest commitReq = req.getCommitRequest();
        commitRequests.put(commitReq.getStartTimestamp(), new RequestAndTimeout(
                request, newTimeout(new CommitRequestTimeoutEvent(commitReq.getStartTimestamp()))));
    } else if (req.hasFenceRequest()) {
        TSOProto.FenceRequest fenceReq = req.getFenceRequest();
        fenceRequests.put(fenceReq.getTableId(), new RequestAndTimeout(
                request, newTimeout(new FenceRequestTimeoutEvent(fenceReq.getTableId()))));
    } else {
        request.error(new IllegalArgumentException("Unknown request type"));
        return;
    }
    ChannelFuture f = channel.write(req);

    f.addListener(new ChannelFutureListener() {
        @Override
        public void operationComplete(ChannelFuture future) {
            if (!future.isSuccess()) {
                fsm.sendEvent(new ErrorEvent(future.getCause()));
            }
        }
    });
}
 
Example #26
Source File: PinpointClientFactoryTest.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@Test
public void reconnectFail() throws InterruptedException {
    // confirm simplified error message when api called.
    int availableTcpPort = SocketUtils.findAvailableTcpPort(47000);
    InetSocketAddress remoteAddress = new InetSocketAddress("127.0.0.1", availableTcpPort);
    ChannelFuture reconnect = clientFactory.reconnect(remoteAddress);
    reconnect.await();
    Assert.assertFalse(reconnect.isSuccess());
    Assert.assertTrue(ConnectException.class.isInstance(reconnect.getCause()));
    
    Thread.sleep(1000);
}
 
Example #27
Source File: DefaultPinpointServer.java    From pinpoint with 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;
    }
}
 
Example #28
Source File: TSOClientRaw.java    From phoenix-omid with 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 #29
Source File: DefaultPinpointClientHandler.java    From pinpoint with 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 #30
Source File: DefaultPinpointClientFactory.java    From pinpoint with Apache License 2.0 5 votes vote down vote up
@VisibleForTesting
ChannelFuture reconnect(final SocketAddress remoteAddress) {
    if (!(remoteAddress instanceof InetSocketAddress)) {
        throw new IllegalArgumentException("invalid remoteAddress:" + remoteAddress);
    }
    SocketAddressProvider socketAddressProvider = new StaticSocketAddressProvider((InetSocketAddress) remoteAddress);
    Connection connection = connectInternal(socketAddressProvider, true);
    return connection.getConnectFuture();
}