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

The following code examples are extracted from open source projects. You can click to vote up the examples that are useful to you.

Example 1

From project bagheera, under directory /src/test/java/com/mozilla/bagheera/http/.

Source file: ContentLengthFilterTest.java

  22 
vote

@Before public void setup(){
  Channel channel=createMock(Channel.class);
  expect(channel.getCloseFuture()).andReturn(new DefaultChannelFuture(channel,false));
  expect(channel.getRemoteAddress()).andReturn(InetSocketAddress.createUnresolved("192.168.1.1",51723));
  OrderedMemoryAwareThreadPoolExecutor executor=new OrderedMemoryAwareThreadPoolExecutor(10,0L,0L);
  final ExecutionHandler handler=new ExecutionHandler(executor,true,true);
  ctx=new FakeChannelHandlerContext(channel,handler);
}
 

Example 2

From project commons-j, under directory /src/main/java/nerds/antelax/commons/net/pubsub/.

Source file: ClientMessageHandler.java

  22 
vote

@Override public void channelDisconnected(final ChannelHandlerContext ctx,final ChannelStateEvent e) throws Exception {
  final Channel c=activeChannel.getAndSet(null);
  if (c != null)   c.close();
  logger.trace("Channel disconnected - active channel unset");
  super.channelDisconnected(ctx,e);
}
 

Example 3

From project Countandra, under directory /src/.

Source file: TestLoad.java

  22 
vote

public void initcassandradb(){
  ClientBootstrap client=new ClientBootstrap(new NioClientSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  client.setPipelineFactory(new ClientPipelineFactory());
  Channel channel;
  HttpRequest request;
  ChannelBuffer buffer;
  channel=client.connect(new InetSocketAddress("127.0.0.1",8080)).awaitUninterruptibly().getChannel();
  request=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"init");
  buffer=ChannelBuffers.copiedBuffer(" ",Charset.defaultCharset());
  request.addHeader(org.jboss.netty.handler.codec.http.HttpHeaders.Names.CONTENT_LENGTH,buffer.readableBytes());
  request.setContent(buffer);
  channel.write(request).awaitUninterruptibly().getChannel().getCloseFuture().awaitUninterruptibly();
  client.releaseExternalResources();
}
 

Example 4

From project fast-http, under directory /src/main/java/org/neo4j/smack/pipeline/http/.

Source file: NettyHttpHandler.java

  22 
vote

@Override public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e) throws Exception {
  Channel ch=e.getChannel();
  Throwable cause=e.getCause();
  Long connectionId=(Long)ctx.getAttachment();
  workBuffer.addFailure(connectionId,ch,cause);
}
 

Example 5

From project floodlight, under directory /src/test/java/net/floodlightcontroller/core/internal/.

Source file: ControllerTest.java

  22 
vote

protected void setupSwitchForAddSwitch(IOFSwitch sw,long dpid){
  String dpidString=HexString.toHexString(dpid);
  OFFeaturesReply featuresReply=new OFFeaturesReply();
  featuresReply.setDatapathId(dpid);
  featuresReply.setPorts(new ArrayList<OFPhysicalPort>());
  expect(sw.getId()).andReturn(dpid).anyTimes();
  expect(sw.getStringId()).andReturn(dpidString).anyTimes();
  expect(sw.getConnectedSince()).andReturn(new Date());
  Channel channel=createMock(Channel.class);
  expect(sw.getChannel()).andReturn(channel);
  expect(channel.getRemoteAddress()).andReturn(null);
  expect(sw.getFeaturesReply()).andReturn(featuresReply).anyTimes();
  expect(sw.getPorts()).andReturn(new ArrayList<OFPhysicalPort>());
}
 

Example 6

From project galaxy, under directory /src/co/paralleluniverse/galaxy/netty/.

Source file: AbstractTcpServer.java

  22 
vote

protected void bind(){
  Channel channel=bootstrap.bind(new InetSocketAddress(port));
  channels.add(channel);
  LOG.info("Channel {} listening on port {}",channel,port);
  setReady(true);
}
 

Example 7

From project gnip4j, under directory /mock-server/src/main/java/com/zaubersoftware/gnip4j/server/netty/.

Source file: HttpGnipServerHandler.java

  22 
vote

@Override public void channelOpen(final ChannelHandlerContext ctx,final ChannelStateEvent e) throws Exception {
  final Channel channel=e.getChannel();
  NettyGnipServer.allChannels.add(channel);
  chunkedInput.setChannel(channel);
  super.channelOpen(ctx,e);
}
 

Example 8

From project httptunnel, under directory /src/main/java/com/yammer/httptunnel/client/.

Source file: HttpTunnelClientChannelSendHandler.java

  22 
vote

@Override public void channelConnected(ChannelHandlerContext ctx,ChannelStateEvent e) throws Exception {
  if (tunnelId == null) {
    if (LOG.isDebugEnabled())     LOG.debug("connection to " + e.getValue() + " succeeded - sending open tunnel request");
    final HttpRequest request=HttpTunnelMessageUtils.createOpenTunnelRequest(tunnelChannel.getServerHostName(),tunnelChannel.getUserAgent());
    final Channel channel=ctx.getChannel();
    final DownstreamMessageEvent event=new DownstreamMessageEvent(channel,Channels.future(channel),request,channel.getRemoteAddress());
    queuedWrites.offer(new TimedMessageEventWrapper(event,requestTimer.time()));
    pendingRequestCount.incrementAndGet();
  }
  this.sendQueuedData(ctx);
}
 

Example 9

From project idigi-java-monitor-api, under directory /netty/src/main/java/com/idigi/api/monitor/netty/.

Source file: ReconnectHandler.java

  22 
vote

@Override public void channelClosed(ChannelHandlerContext ctx,ChannelStateEvent e){
  if (this.enabled) {
    logger.info("Reconnecting to: {}",getRemoteAddress());
    Channel newChannel=bootstrap.connect().getChannel();
    notifyChannelChangedListener(newChannel);
  }
 else {
    logger.debug("Skipping reconnect.");
  }
}
 

Example 10

From project incubator-s4, under directory /subprojects/s4-comm/src/main/java/org/apache/s4/comm/tcp/.

Source file: TCPEmitter.java

  22 
vote

private void sendMessage(int partitionId,byte[] message){
  ChannelBuffer buffer=ChannelBuffers.buffer(message.length);
  buffer.writeBytes(message);
  if (!partitionChannelMap.containsKey(partitionId)) {
    if (!connectTo(partitionId)) {
      return;
    }
  }
  Channel c=partitionChannelMap.get(partitionId);
  if (c == null)   return;
  c.write(buffer).addListener(new MessageSendingListener(partitionId));
}
 

Example 11

From project JMaNGOS, under directory /Commons/src/main/java/org/jmangos/commons/network/service/.

Source file: AbstractNetworkService.java

  22 
vote

/** 
 * Creates the server channel.
 * @param address the address
 * @param pipelineFactory the pipeline factory
 */
protected void createServerChannel(final InetSocketAddress address,final ChannelPipelineFactory pipelineFactory){
  final ServerChannelFactory channelFactory=new ServerChannelFactory(address);
  channelFactory.initialize(pipelineFactory);
  final Channel channel=channelFactory.connect();
  log.info("Initialized server channel : " + channel.getLocalAddress());
}
 

Example 12

From project adbcj, under directory /mysql/netty/src/main/java/org/adbcj/mysql/netty/.

Source file: MysqlConnectionManager.java

  21 
vote

public MysqlConnectFuture(ChannelFuture channelFuture){
  this.channelFuture=channelFuture;
  channelFuture.addListener(new ChannelFutureListener(){
    @Override public void operationComplete(    ChannelFuture future) throws Exception {
      logger.debug("Connect completed");
      Channel channel=future.getChannel();
      MysqlConnection connection=new MysqlConnection(MysqlConnectionManager.this,getCredentials(),channel,MysqlConnectFuture.this);
      channel.getPipeline().addLast("handler",new Handler(connection));
      MessageQueuingHandler queuingHandler=channel.getPipeline().get(MessageQueuingHandler.class);
synchronized (queuingHandler) {
        queuingHandler.flush();
        channel.getPipeline().remove(queuingHandler);
      }
    }
  }
);
}
 

Example 13

From project ardverk-dht, under directory /components/http/src/main/java/org/ardverk/dht/http/.

Source file: HttpTransport.java

  21 
vote

@Override public void send(final KUID contactId,final Message message,long timeout,TimeUnit unit) throws IOException {
  SocketAddress addr=message.getAddress();
  SocketAddress endpoint=NetworkUtils.getResolved(addr);
  ChannelFuture future=null;
  try {
    future=connect(endpoint,timeout,unit);
  }
 catch (  Exception err) {
    LOG.error("Exception",err);
    handleException(message,err);
    return;
  }
  future.addListener(new ChannelFutureListener(){
    @Override public void operationComplete(    ChannelFuture connectFuture) throws IOException {
      if (!connectFuture.isSuccess()) {
        handleException(message,connectFuture.getCause());
        return;
      }
      ByteArrayOutputStream baos=new ByteArrayOutputStream();
      Encoder encoder=codec.createEncoder(baos);
      encoder.write(message);
      encoder.close();
      byte[] encoded=baos.toByteArray();
      HttpRequest httpRequest=new DefaultHttpRequest(HttpVersion.HTTP_1_1,HttpMethod.POST,"/ardverk");
      httpRequest.setContent(ChannelBuffers.copiedBuffer(encoded));
      httpRequest.setHeader(HttpHeaders.Names.CONTENT_LENGTH,encoded.length);
      httpRequest.setHeader(HttpHeaders.Names.CONNECTION,HttpHeaders.Values.CLOSE);
      Channel channel=connectFuture.getChannel();
      ChannelFuture future=channel.write(httpRequest);
      future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
      future.addListener(new MessageListener(contactId,message));
    }
  }
);
}
 

Example 14

From project chililog-server, under directory /src/main/java/org/chililog/server/pubsub/jsonhttp/.

Source file: JsonHttpService.java

  21 
vote

/** 
 * Start all pubsub services
 */
public synchronized void start(){
  _mqProducerSessionPool=new MqProducerSessionPool(AppProperties.getInstance().getPubSubJsonHttpNettyHandlerThreadPoolSize());
  AppProperties appProperties=AppProperties.getInstance();
  if (_channelFactory != null) {
    _logger.info("PubSub JSON HTTP Web Sever Already Started.");
    return;
  }
  _logger.info("Starting PubSub JSON HTTP  Web Sever on " + appProperties.getPubSubJsonHttpHost() + ":"+ appProperties.getPubSubJsonHttpPort()+ "...");
  int workerCount=appProperties.getPubSubJsonHttpNettyWorkerThreadPoolSize();
  if (workerCount == 0) {
    _channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  }
 else {
    _channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool(),workerCount);
  }
  ServerBootstrap bootstrap=new ServerBootstrap(_channelFactory);
  Executor executor=Executors.newFixedThreadPool(appProperties.getPubSubJsonHttpNettyHandlerThreadPoolSize());
  bootstrap.setPipelineFactory(new JsonHttpServerPipelineFactory(executor));
  String[] hosts=TransportConfiguration.splitHosts(appProperties.getPubSubJsonHttpHost());
  for (  String h : hosts) {
    if (StringUtils.isBlank(h)) {
      if (hosts.length == 1) {
        h="0.0.0.0";
      }
 else {
        continue;
      }
    }
    SocketAddress address=h.equals("0.0.0.0") ? new InetSocketAddress(appProperties.getPubSubJsonHttpPort()) : new InetSocketAddress(h,appProperties.getPubSubJsonHttpPort());
    Channel channel=bootstrap.bind(address);
    _allChannels.add(channel);
  }
  _logger.info("PubSub JSON HTTP Web Sever Started.");
}
 

Example 15

From project cloudhopper-smpp, under directory /src/main/java/com/cloudhopper/smpp/channel/.

Source file: SmppServerConnector.java

  21 
vote

@Override public void channelConnected(ChannelHandlerContext ctx,ChannelStateEvent e) throws Exception {
  Channel channel=e.getChannel();
  channels.add(channel);
  this.server.getCounters().incrementChannelConnectsAndGet();
  String channelName=ChannelUtil.createChannelName(channel);
  String threadName=server.getConfiguration().getName() + ".UnboundSession." + channelName;
  String currentThreadName=Thread.currentThread().getName();
  Thread.currentThread().setName(server.getConfiguration().getName());
  logger.info("New channel from [{}]",channelName);
  Thread.currentThread().setName(currentThreadName);
  channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_THREAD_RENAMER_NAME,new SmppSessionThreadRenamer(threadName));
  channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_PDU_DECODER_NAME,new SmppSessionPduDecoder(server.getTranscoder()));
  UnboundSmppSession session=new UnboundSmppSession(channelName,channel,server);
  channel.getPipeline().addLast(SmppChannelConstants.PIPELINE_SESSION_WRAPPER_NAME,new SmppSessionWrapper(session));
}
 

Example 16

From project dragon, under directory /hadoop-dragon-core/src/main/java/org/apache/hadoop/realtime/shuffle/.

Source file: ShuffleEventEmitter.java

  21 
vote

@Override public boolean emitEvent(final Event<KEY,VALUE> event) throws IOException, InterruptedException {
  int partition=partitioner.getPartition(event,partitions);
  if (partition < 0 || partition >= partitions) {
    throw new IOException("Illegal partition for " + event + " ("+ partition+ ")");
  }
  boolean isRemoteNNHealthy=true;
  if (!isRemoteNNHealthy || failures[partition] > 0) {
    saveEventToLocal(event);
  }
 else {
    final long beginTime=System.currentTimeMillis();
    final Channel channel=futures.get(partition).getChannel();
    ChannelFuture writeFuture=futures.get(partition).getChannel().write(event);
    writeFuture.addListener(new ChannelFutureListener(){
      @Override public void operationComplete(      ChannelFuture future) throws Exception {
        if (future.isSuccess()) {
          return;
        }
        String errorMsg="";
        if (System.currentTimeMillis() - beginTime >= 100) {
          errorMsg="write to send buffer consume too long time(" + (System.currentTimeMillis() - beginTime) + "),request id is:"+ event.offset();
        }
        if (future.isCancelled()) {
          errorMsg="Send request to " + channel.toString() + " cancelled by user,request id is:"+ event.offset();
        }
        if (!future.isSuccess()) {
          if (channel.isConnected()) {
            channel.close();
          }
 else {
          }
          errorMsg="Send request to " + channel.toString() + " error"+ future.getCause();
        }
        LOG.error(errorMsg);
      }
    }
);
  }
  return false;
}
 

Example 17

From project enterprise, under directory /com/src/main/java/org/neo4j/com/.

Source file: Server.java

  21 
vote

public Server(T requestTarget,final int port,StringLogger logger,int frameLength,byte applicationProtocolVersion,int maxNumberOfConcurrentTransactions,int oldChannelThreshold,TxChecksumVerifier txVerifier,int chunkSize){
  assertChunkSizeIsWithinFrameSize(chunkSize,frameLength);
  this.requestTarget=requestTarget;
  this.frameLength=frameLength;
  this.chunkSize=chunkSize;
  this.applicationProtocolVersion=applicationProtocolVersion;
  this.msgLog=logger;
  this.txVerifier=txVerifier;
  this.oldChannelThresholdMillis=oldChannelThreshold * 1000;
  executor=Executors.newCachedThreadPool();
  targetCallExecutor=Executors.newCachedThreadPool(new NamedThreadFactory(getClass().getSimpleName() + ":" + port));
  unfinishedTransactionExecutor=Executors.newScheduledThreadPool(2);
  channelFactory=new NioServerSocketChannelFactory(executor,executor,maxNumberOfConcurrentTransactions);
  silentChannelExecutor=Executors.newSingleThreadScheduledExecutor();
  silentChannelExecutor.scheduleWithFixedDelay(silentChannelFinisher(),5,5,TimeUnit.SECONDS);
  bootstrap=new ServerBootstrap(channelFactory);
  bootstrap.setPipelineFactory(this);
  Channel channel;
  try {
    channel=bootstrap.bind(new InetSocketAddress(port));
  }
 catch (  ChannelException e) {
    msgLog.logMessage("Failed to bind server to port " + port,e);
    executor.shutdown();
    throw e;
  }
  channelGroup=new DefaultChannelGroup();
  channelGroup.add(channel);
  msgLog.logMessage(getClass().getSimpleName() + " communication server started and bound to " + port,true);
}
 

Example 18

From project flazr, under directory /src/main/java/com/flazr/rtmp/proxy/.

Source file: ProxyHandler.java

  21 
vote

@Override public void channelOpen(ChannelHandlerContext ctx,ChannelStateEvent e){
  final Channel inboundChannel=e.getChannel();
  RtmpProxy.ALL_CHANNELS.add(inboundChannel);
  inboundChannel.setReadable(false);
  ClientBootstrap cb=new ClientBootstrap(cf);
  cb.getPipeline().addLast("handshaker",new ProxyHandshakeHandler());
  cb.getPipeline().addLast("handler",new OutboundHandler(e.getChannel()));
  ChannelFuture f=cb.connect(new InetSocketAddress(remoteHost,remotePort));
  outboundChannel=f.getChannel();
  f.addListener(new ChannelFutureListener(){
    @Override public void operationComplete(    ChannelFuture future) throws Exception {
      if (future.isSuccess()) {
        logger.info("connected to remote host: {}, port: {}",remoteHost,remotePort);
        inboundChannel.setReadable(true);
      }
 else {
        inboundChannel.close();
      }
    }
  }
);
}
 

Example 19

From project giraph, under directory /src/main/java/org/apache/giraph/comm/netty/.

Source file: NettyClient.java

  21 
vote

/** 
 * Get the next available channel, reconnecting if necessary
 * @param remoteServer Remote server to get a channel for
 * @return Available channel for this remote server
 */
private Channel getNextChannel(InetSocketAddress remoteServer){
  Channel channel=addressChannelMap.get(remoteServer).nextChannel();
  if (channel == null) {
    throw new IllegalStateException("getNextChannel: No channel exists for " + remoteServer);
  }
  if (channel.isConnected()) {
    return channel;
  }
  addressChannelMap.get(remoteServer).removeLast();
  if (LOG.isInfoEnabled()) {
    LOG.info("getNextChannel: Fixing disconnected channel to " + remoteServer + ", open = "+ channel.isOpen()+ ", "+ "bound = "+ channel.isBound());
  }
  int reconnectFailures=0;
  while (reconnectFailures < maxConnectionFailures) {
    ChannelFuture connectionFuture=bootstrap.connect(remoteServer);
    connectionFuture.awaitUninterruptibly();
    if (connectionFuture.isSuccess()) {
      if (LOG.isInfoEnabled()) {
        LOG.info("getNextChannel: Connected to " + remoteServer + "!");
      }
      addressChannelMap.get(remoteServer).addChannel(connectionFuture.getChannel());
      return connectionFuture.getChannel();
    }
    ++reconnectFailures;
    LOG.warn("getNextChannel: Failed to reconnect to " + remoteServer + " on attempt "+ reconnectFailures+ " out of "+ maxConnectionFailures+ " max attempts, sleeping for 5 secs",connectionFuture.getCause());
    try {
      Thread.sleep(5000);
    }
 catch (    InterruptedException e) {
      LOG.warn("getNextChannel: Unexpected interrupted exception",e);
    }
  }
  throw new IllegalStateException("getNextChannel: Failed to connect " + "to " + remoteServer + " in "+ reconnectFailures+ " connect attempts");
}
 

Example 20

From project hotpotato, under directory /src/functionaltest/java/com/biasedbit/hotpotato/pipelining/.

Source file: Http11PipeliningTestServer.java

  21 
vote

public boolean init(){
  NioServerSocketChannelFactory channelFactory=new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool());
  this.bootstrap=new ServerBootstrap(channelFactory);
  this.packetCounter=new MessageCounter();
  this.httpRequestCounter=new MessageCounter();
  this.bootstrap.setPipelineFactory(new ChannelPipelineFactory(){
    @Override public ChannelPipeline getPipeline() throws Exception {
      ChannelPipeline pipeline=Channels.pipeline();
      pipeline.addLast("packetCounter",packetCounter);
      pipeline.addLast("encoder",new HttpResponseEncoder());
      pipeline.addLast("decoder",new HttpRequestDecoder());
      pipeline.addLast("httpRequestCounter",httpRequestCounter);
      pipeline.addLast("handler",new ServerHandler());
      return pipeline;
    }
  }
);
  this.channelGroup=new DefaultChannelGroup("pipelining-server");
  SocketAddress bindAddress;
  if (this.host != null) {
    bindAddress=new InetSocketAddress(this.host,this.port);
  }
 else {
    bindAddress=new InetSocketAddress(this.port);
  }
  Channel serverChannel=this.bootstrap.bind(bindAddress);
  this.channelGroup.add(serverChannel);
  return (this.running=serverChannel.isBound());
}
 

Example 21

From project http-client, under directory /src/main/java/com/biasedbit/http/.

Source file: DummyHttpServer.java

  21 
vote

public boolean init(){
  if (this.useOldIo) {
    this.bootstrap=new ServerBootstrap(new OioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  }
 else {
    this.bootstrap=new ServerBootstrap(new NioServerSocketChannelFactory(Executors.newCachedThreadPool(),Executors.newCachedThreadPool()));
  }
  this.bootstrap.setOption("child.tcpNoDelay",true);
  this.bootstrap.setPipelineFactory(new ChannelPipelineFactory(){
    @Override public ChannelPipeline getPipeline() throws Exception {
      ChannelPipeline pipeline=Channels.pipeline();
      if (useSsl) {
        SSLEngine engine=BogusSslContextFactory.getInstance().getServerContext().createSSLEngine();
        engine.setUseClientMode(false);
        pipeline.addLast("ssl",new SslHandler(engine));
      }
      pipeline.addLast("encoder",new HttpResponseEncoder());
      pipeline.addLast("decoder",new HttpRequestDecoder());
      pipeline.addLast("aggregator",new HttpChunkAggregator(5242880));
      pipeline.addLast("handler",new RequestHandler());
      return pipeline;
    }
  }
);
  this.channelGroup=new DefaultChannelGroup("hotpotato-http-server-" + Integer.toHexString(this.hashCode()));
  SocketAddress bindAddress;
  if (this.host != null) {
    bindAddress=new InetSocketAddress(this.host,this.port);
  }
 else {
    bindAddress=new InetSocketAddress(this.port);
  }
  Channel serverChannel=this.bootstrap.bind(bindAddress);
  this.channelGroup.add(serverChannel);
  return (this.running=serverChannel.isBound());
}
 

Example 22

From project james, under directory /protocols-imap4/src/main/java/org/apache/james/imapserver/netty/.

Source file: ImapChannelUpstreamHandler.java

  21 
vote

@Override public void exceptionCaught(ChannelHandlerContext ctx,ExceptionEvent e) throws Exception {
  getLogger(ctx.getChannel()).debug("Error while processing imap request",e.getCause());
  if (e.getCause() instanceof TooLongFrameException) {
    ImapResponseComposer composer=(ImapResponseComposer)ctx.getAttachment();
    composer.untaggedResponse(ImapConstants.BAD + " failed. Maximum command line length exceeded");
  }
 else {
    final ImapSession imapSession=(ImapSession)attributes.get(ctx.getChannel());
    if (imapSession != null)     imapSession.logout();
    Channel channel=ctx.getChannel();
    if (channel.isConnected()) {
      channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
    }
  }
}
 

Example 23

From project avro, under directory /lang/java/ipc/src/main/java/org/apache/avro/ipc/.

Source file: NettyTransceiver.java

  19 
vote

/** 
 * Gets the Netty channel.  If the channel is not connected, first attempts  to connect. NOTE: The stateLock read lock *must* be acquired before calling this  method.
 * @return the Netty channel
 * @throws IOException if an error occurs connecting the channel.
 */
private Channel getChannel() throws IOException {
  if (!isChannelReady(channel)) {
    stateLock.readLock().unlock();
    stateLock.writeLock().lock();
    try {
      if (!isChannelReady(channel)) {
synchronized (channelFutureLock) {
          if (!stopping) {
            LOG.debug("Connecting to " + remoteAddr);
            channelFuture=bootstrap.connect(remoteAddr);
          }
        }
        if (channelFuture != null) {
          channelFuture.awaitUninterruptibly(connectTimeoutMillis);
synchronized (channelFutureLock) {
            if (!channelFuture.isSuccess()) {
              throw new IOException("Error connecting to " + remoteAddr,channelFuture.getCause());
            }
            channel=channelFuture.getChannel();
            channelFuture=null;
          }
        }
      }
    }
  finally {
      stateLock.readLock().lock();
      stateLock.writeLock().unlock();
    }
  }
  return channel;
}
 

Example 24

From project bbb-java, under directory /src/main/java/org/mconf/bbb/chat/.

Source file: ChatModule.java

  19 
vote

public ChatModule(MainRtmpConnection handler,Channel channel){
  super(handler,channel);
  if (handler.getContext().getJoinService().getApplicationService().getVersion().equals(ApplicationService.VERSION_0_7))   MESSAGE_ENCODING=MESSAGE_ENCODING_STRING;
 else   MESSAGE_ENCODING=MESSAGE_ENCODING_TYPED_OBJECT;
  publicChatSO=handler.getSharedObject("chatSO",false);
  publicChatSO.addSharedObjectListener(this);
  publicChatSO.connect(channel);
  privateChatSO=handler.getSharedObject(Integer.toString(handler.getContext().getMyUserId()),false);
  privateChatSO.addSharedObjectListener(this);
  privateChatSO.connect(channel);
}
 

Example 25

From project efflux, under directory /src/main/java/com/biasedbit/efflux/network/.

Source file: DataPacketDecoder.java

  19 
vote

@Override protected Object decode(ChannelHandlerContext ctx,Channel channel,Object msg) throws Exception {
  if (!(msg instanceof ChannelBuffer)) {
    return null;
  }
  try {
    return DataPacket.decode((ChannelBuffer)msg);
  }
 catch (  Exception e) {
    LOG.debug("Failed to decode RTP packet.",e);
    return null;
  }
}
 

Example 26

From project java-webserver, under directory /src/org/nikki/http/fastcgi/net/.

Source file: FastCGIEncoder.java

  19 
vote

@Override protected Object encode(ChannelHandlerContext ctx,Channel channel,Object object) throws Exception {
  if (object instanceof FastCGIRequest) {
    return ((FastCGIRequest)object).toBuffer();
  }
  return null;
}