Search in sources :

Example 26 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project dubbo by alibaba.

the class NettyClient method doConnect.

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
                // copy reference
                Channel oldChannel = NettyClient.this.channel;
                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();
        }
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Channel(org.jboss.netty.channel.Channel) RemotingException(com.alibaba.dubbo.remoting.RemotingException)

Example 27 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project Protocol-Adapter-OSLP by OSGP.

the class OslpChannelHandler method send.

public OslpEnvelope send(final InetSocketAddress address, final OslpEnvelope request, final String deviceIdentification) throws IOException, DeviceSimulatorException {
    LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
    final Callback callback = new Callback(this.connectionTimeout);
    this.lock.lock();
    // Open connection and send message
    ChannelFuture channelFuture = null;
    try {
        channelFuture = this.bootstrap.connect(address);
        channelFuture.awaitUninterruptibly(this.connectionTimeout, TimeUnit.MILLISECONDS);
        if (channelFuture.getChannel() != null && channelFuture.getChannel().isConnected()) {
            LOGGER.info("Connection established to: {}", address);
        } else {
            LOGGER.info("The connnection to the device {} is not successfull", deviceIdentification);
            LOGGER.warn("Unable to connect to: {}", address);
            throw new IOException("Unable to connect");
        }
        this.callbacks.put(channelFuture.getChannel().getId(), callback);
        channelFuture.getChannel().write(request);
    } finally {
        this.lock.unlock();
    }
    // wait for response and close connection
    try {
        final OslpEnvelope response = callback.get(deviceIdentification);
        LOGGER.info("Received OSLP response (after callback): {}", response.getPayloadMessage());
        /*
             * Devices expect the channel to be closed if (and only if) the
             * platform initiated the conversation. If the device initiated the
             * conversation it needs to close the channel itself.
             */
        channelFuture.getChannel().close();
        return response;
    } catch (final IOException | DeviceSimulatorException e) {
        LOGGER.error("send exception", e);
        // Remove callback when exception has occurred
        this.callbacks.remove(channelFuture.getChannel().getId());
        throw e;
    }
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DeviceSimulatorException(com.alliander.osgp.webdevicesimulator.exceptions.DeviceSimulatorException) IOException(java.io.IOException) OslpEnvelope(com.alliander.osgp.oslp.OslpEnvelope)

Example 28 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project Protocol-Adapter-OSLP by OSGP.

the class OslpChannelHandlerClient method send.

public void send(final InetSocketAddress address, final OslpEnvelope request, final OslpResponseHandler responseHandler, final String deviceIdentification) throws IOException {
    LOGGER.info("Sending OSLP request: {}", request.getPayloadMessage());
    // Open connection and send message.
    final ChannelFuture channelFuture = this.bootstrap.connect(address);
    this.callbackHandlers.put(channelFuture.getChannel().getId(), new OslpCallbackHandler(responseHandler));
    channelFuture.addListener(new ChannelFutureListener() {

        @Autowired
        protected DeviceResponseMessageSender responseMessageSender;

        @Override
        public void operationComplete(final ChannelFuture future) throws Exception {
            if (future.isSuccess()) {
                OslpChannelHandlerClient.this.write(future, address, request);
                // What is this call below good for?
                future.getChannel().getId();
            } else {
                LOGGER.info("The connection to the device {} is not successful", deviceIdentification);
                throw new IOException("ChannelFuture - Unable to connect");
            }
        }
    });
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) Autowired(org.springframework.beans.factory.annotation.Autowired) DeviceResponseMessageSender(com.alliander.osgp.adapter.protocol.oslp.elster.infra.messaging.DeviceResponseMessageSender) IOException(java.io.IOException) ChannelFutureListener(org.jboss.netty.channel.ChannelFutureListener) IOException(java.io.IOException) NoDeviceResponseException(com.alliander.osgp.shared.exceptionhandling.NoDeviceResponseException)

Example 29 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project load-balancer by RestComm.

the class TestHA method writeResponse.

private void writeResponse(MessageEvent e, HttpResponseStatus status, String command) {
    JsonObject jo = new JsonObject();
    jo.addProperty(command, Protocol.OK);
    ChannelBuffer buf = ChannelBuffers.copiedBuffer(jo.toString(), Charset.forName("UTF-8"));
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    response.setHeader(HttpHeaders.Names.CONTENT_TYPE, APPLICATION_JSON);
    response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buf.readableBytes());
    response.setContent(buf);
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) JsonObject(com.google.gson.JsonObject) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Example 30 with ChannelFuture

use of org.jboss.netty.channel.ChannelFuture in project load-balancer by RestComm.

the class TestNodeRegister method writeResponse.

private void writeResponse(MessageEvent e, HttpResponseStatus status, String command) {
    Packet packet = null;
    switch(command) {
        case Protocol.HEARTBEAT:
            packet = new HeartbeatResponsePacket(Protocol.OK);
            break;
        case Protocol.START:
            packet = new StartResponsePacket(Protocol.OK);
            break;
        case Protocol.SHUTDOWN:
            packet = new ShutdownResponsePacket(Protocol.OK);
            break;
    }
    ChannelBuffer buf = ChannelBuffers.copiedBuffer(gson.toJson(packet), Charset.forName("UTF-8"));
    HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, status);
    response.setHeader(HttpHeaders.Names.CONTENT_TYPE, APPLICATION_JSON);
    response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, buf.readableBytes());
    response.setContent(buf);
    ChannelFuture future = e.getChannel().write(response);
    future.addListener(ChannelFutureListener.CLOSE);
}
Also used : ChannelFuture(org.jboss.netty.channel.ChannelFuture) HeartbeatResponsePacket(org.mobicents.tools.heartbeat.packets.HeartbeatResponsePacket) ShutdownResponsePacket(org.mobicents.tools.heartbeat.packets.ShutdownResponsePacket) StartResponsePacket(org.mobicents.tools.heartbeat.packets.StartResponsePacket) Packet(org.mobicents.tools.heartbeat.api.Packet) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) StartResponsePacket(org.mobicents.tools.heartbeat.packets.StartResponsePacket) HeartbeatResponsePacket(org.mobicents.tools.heartbeat.packets.HeartbeatResponsePacket) DefaultHttpResponse(org.jboss.netty.handler.codec.http.DefaultHttpResponse) HttpResponse(org.jboss.netty.handler.codec.http.HttpResponse) ShutdownResponsePacket(org.mobicents.tools.heartbeat.packets.ShutdownResponsePacket) ChannelBuffer(org.jboss.netty.buffer.ChannelBuffer)

Aggregations

ChannelFuture (org.jboss.netty.channel.ChannelFuture)138 Channel (org.jboss.netty.channel.Channel)40 DefaultHttpResponse (org.jboss.netty.handler.codec.http.DefaultHttpResponse)38 HttpResponse (org.jboss.netty.handler.codec.http.HttpResponse)28 ChannelBuffer (org.jboss.netty.buffer.ChannelBuffer)27 HttpRequest (org.jboss.netty.handler.codec.http.HttpRequest)26 InetSocketAddress (java.net.InetSocketAddress)25 ChannelFutureListener (org.jboss.netty.channel.ChannelFutureListener)23 DefaultHttpRequest (org.jboss.netty.handler.codec.http.DefaultHttpRequest)23 Test (org.junit.Test)15 SucceededChannelFuture (org.jboss.netty.channel.SucceededChannelFuture)13 ClientBootstrap (org.jboss.netty.bootstrap.ClientBootstrap)12 InvocationOnMock (org.mockito.invocation.InvocationOnMock)12 PrepareForTest (org.powermock.core.classloader.annotations.PrepareForTest)10 NioClientSocketChannelFactory (org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory)9 Test (org.testng.annotations.Test)8 IOException (java.io.IOException)7 ConnectException (java.net.ConnectException)7 ArrayList (java.util.ArrayList)7 HashMap (java.util.HashMap)6