/**
  * Interface method implementation. Reads and processes commands sent to the service proxy.
  * Expects data in the command protocol defined in the class summary. Discards commands that do
  * not have a {@link TaskHandler} mapping.
  *
  * @see
  *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#handleUpstream(org.jboss.netty.channel.ChannelHandlerContext,
  *     org.jboss.netty.channel.ChannelEvent)
  */
 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent event) throws Exception {
   if (MessageEvent.class.isAssignableFrom(event.getClass())) {
     CommandInterpreter commandInterpreter = new CommandInterpreter();
     CommandInterpreter.ProxyCommand readCommand =
         commandInterpreter.readCommand((MessageEvent) event);
     LOGGER.debug("Read Command : " + readCommand);
     String pool = readCommand.getCommandParams().get("pool");
     TaskHandlerExecutor executor;
     // Try to execute command using ThreadPool, if "pool" is found in the command, else the
     // command name
     if (pool != null) {
       executor = this.repository.get(readCommand.getCommand(), pool);
     } else {
       executor = this.repository.get(readCommand.getCommand(), readCommand.getCommand());
     }
     executor.setParams(readCommand.getCommandParams());
     executor.setData(readCommand.getCommandData());
     try {
       TaskResult result = executor.execute();
       LOGGER.debug("The output is: " + result);
       // write the results to the channel output
       commandInterpreter.writeCommandExecutionResponse(ctx, event, result);
     } catch (Exception e) {
       LOGGER.error("Error in executing command/fallBack : " + readCommand, e);
       throw new RuntimeException("Error in executing command : " + readCommand, e);
     }
   }
   super.handleUpstream(ctx, event);
 }
 @Override
 public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof ChannelStateEvent) {
     logger.info(e.toString());
   }
   super.handleUpstream(ctx, e);
 }
 /**
  * called upon disconnect from the server.
  *
  * @param ctx the channel context
  * @param channelStateEvent the channel disconnect event
  * @throws Exception an exception
  */
 @Override
 public final void channelDisconnected(
     final ChannelHandlerContext ctx, final ChannelStateEvent channelStateEvent)
     throws Exception { // NOPMD
   super.channelDisconnected(ctx, channelStateEvent);
   shutdown();
 }
Example #4
0
 @Override
 public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   context.getWorkers().put(ctx.getChannel(), new MasterWorkerHolder(ctx.getChannel()));
   Channel channel = ctx.getChannel();
   SocketAddress addr = channel.getRemoteAddress();
   SocketLog.info("worker connected , :" + addr.toString());
   super.channelConnected(ctx, e);
 }
 @Override
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   // as seen in http://www.jboss.org/netty/community.html#nabble-td2423020
   super.channelOpen(ctx, e);
   if (group != null) {
     group.add(ctx.getChannel());
   }
 }
  /**
   * Attention please,
   *
   * @see
   *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelDisconnected(org.jboss.netty.channel.ChannelHandlerContext,
   *     org.jboss.netty.channel.ChannelStateEvent)
   */
  @Override
  public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    LOG.info(
        "Receive channelDisconnected to {}, channel = {}", client.getRemoteAddr(), e.getChannel());
    // ctx.sendUpstream(e);
    super.channelDisconnected(ctx, e);

    client.disconnectChannel(e.getChannel());
  }
  @Override
  public void channelBound(final ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {

    ImapSession imapsession =
        new NettyImapSession(
            ctx.getChannel(), logger, context, enabledCipherSuites, compress, plainAuthDisallowed);
    attributes.set(ctx.getChannel(), imapsession);
    super.channelBound(ctx, e);
  }
Example #8
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    final Channel channel = ctx.getChannel();
    SocketMessage sm = (SocketMessage) e.getMessage();
    if (sm.getKind() == Kind.REQUEST) {
      final Request request = Request.newBuilder().mergeFrom(sm.getBody()).build();
      if (request.getOperate() == Operate.HeartBeat) {
        beHeartBeat.beHeartBeat(context, channel, request);
      }
    } else if (sm.getKind() == Kind.WEB_REUQEST) {
      final WebRequest request = WebRequest.newBuilder().mergeFrom(sm.getBody()).build();
      if (request.getOperate() == WebOperate.ExecuteJob) {
        completionService.submit(
            new Callable<ChannelResponse>() {
              public ChannelResponse call() throws Exception {
                return new ChannelResponse(channel, beWebExecute.beWebExecute(context, request));
              }
            });
      } else if (request.getOperate() == WebOperate.CancelJob) {
        completionService.submit(
            new Callable<ChannelResponse>() {
              public ChannelResponse call() throws Exception {
                return new ChannelResponse(channel, beWebCancel.beWebCancel(context, request));
              }
            });
      } else if (request.getOperate() == WebOperate.UpdateJob) {
        completionService.submit(
            new Callable<ChannelResponse>() {
              public ChannelResponse call() throws Exception {
                return new ChannelResponse(channel, beUpdate.beWebUpdate(context, request));
              }
            });
      } else if (request.getOperate() == WebOperate.ExecuteDebug) {
        completionService.submit(
            new Callable<ChannelResponse>() {
              public ChannelResponse call() throws Exception {
                return new ChannelResponse(channel, beDebug.beWebExecute(context, request));
              }
            });
      }
    } else if (sm.getKind() == Kind.RESPONSE) {
      for (ResponseListener lis : new ArrayList<ResponseListener>(listeners)) {
        lis.onResponse(Response.newBuilder().mergeFrom(sm.getBody()).build());
      }
    } else if (sm.getKind() == Kind.WEB_RESPONSE) {
      for (ResponseListener lis : new ArrayList<ResponseListener>(listeners)) {
        lis.onWebResponse(WebResponse.newBuilder().mergeFrom(sm.getBody()).build());
      }
    }

    super.messageReceived(ctx, e);
  }
  @Override
  public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
    getLogger(ctx.getChannel())
        .info("Connection closed for " + address.getAddress().getHostAddress());

    // remove the stored attribute for the channel to free up resources
    // See JAMES-1195
    ImapSession imapSession = (ImapSession) attributes.remove(ctx.getChannel());
    if (imapSession != null) imapSession.logout();

    super.channelClosed(ctx, e);
  }
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent evt) throws Exception {
   // Clear the map for this context
   try {
     Logs.extreme()
         .debug(
             "Removing data map on channel closed event for channel: " + ctx.getChannel().getId());
     dataMap.remove(ctx.getChannel());
   } catch (final Throwable f) {
     // Nothing to lookup.
   } finally {
     super.channelClosed(ctx, evt);
   }
 }
Example #11
0
 @Override
 public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
   if (e.getCause() instanceof JsonParseException) {
     BaseTransport.respond(
         e.getChannel(), HttpResponseStatus.INTERNAL_SERVER_ERROR, "Broken JSON encoding.");
   } else if (e.getCause() instanceof SessionHandler.NotFoundException) {
     BaseTransport.respond(
         e.getChannel(),
         HttpResponseStatus.NOT_FOUND,
         "Session not found. Cannot send data to non-existing session.");
   } else {
     super.exceptionCaught(ctx, e);
   }
 }
  @Override
  public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
    InetSocketAddress address = (InetSocketAddress) ctx.getChannel().getRemoteAddress();
    getLogger(ctx.getChannel())
        .info("Connection established from " + address.getAddress().getHostAddress());

    ImapResponseComposer response =
        new ImapResponseComposerImpl(new ChannelImapResponseWriter(ctx.getChannel()));
    ctx.setAttachment(response);

    // write hello to client
    response.untagged().message("OK").message(hello).end();
    super.channelConnected(ctx, e);
  }
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   if (e.getMessage() == null) {
     return;
   } else if (e.getMessage() instanceof byte[]) {
     byte[] bytes = (byte[]) e.getMessage();
     Object msg;
     if (bytes.length == 0) {
       msg = Heartbeat.getSingleton();
     } else {
       try {
         msg = serializer.deserialize(bytes);
       } catch (Exception ex) {
         throw ex;
       }
     }
     UpstreamMessageEvent event =
         new UpstreamMessageEvent(e.getChannel(), msg, e.getRemoteAddress());
     super.messageReceived(ctx, event);
   } else {
     super.messageReceived(ctx, e);
   }
 }
Example #14
0
  /* (non-Javadoc)
   * @see org.jboss.netty.channel.SimpleChannelUpstreamHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
   */
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    Message message = (Message) e.getMessage();
    long commandId = ((Long) message.getHeader().getCommandId()).longValue();
    if (commandId != packetType.getCommandId()) {
      super.messageReceived(ctx, e);
      return;
    }

    ReportRequestMessage requestMessage = (ReportRequestMessage) message;
    ReportResponseMessage responseMessage = new ReportResponseMessage();

    responseMessage.setRequest(requestMessage);

    ctx.getChannel().write(responseMessage);

    ((Session) ctx.getChannel().getAttachment())
        .receive(requestMessage.setResponse(responseMessage));
  }
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    ImapSession session = (ImapSession) attributes.get(ctx.getChannel());
    ImapResponseComposer response = (ImapResponseComposer) ctx.getAttachment();
    ImapMessage message = (ImapMessage) e.getMessage();
    ChannelPipeline cp = ctx.getPipeline();

    try {
      if (cp.get(NettyConstants.EXECUTION_HANDLER) != null) {
        cp.addBefore(
            NettyConstants.EXECUTION_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
      } else {
        cp.addBefore(
            NettyConstants.CORE_HANDLER, NettyConstants.HEARTBEAT_HANDLER, heartbeatHandler);
      }
      final ResponseEncoder responseEncoder = new ResponseEncoder(encoder, response, session);
      processor.process(message, responseEncoder, session);

      if (session.getState() == ImapSessionState.LOGOUT) {
        // Make sure we close the channel after all the buffers were flushed out
        Channel channel = ctx.getChannel();
        if (channel.isConnected()) {
          channel.write(ChannelBuffers.EMPTY_BUFFER).addListener(ChannelFutureListener.CLOSE);
        }
      }
      final IOException failure = responseEncoder.getFailure();

      if (failure != null) {
        final Logger logger = session.getLog();
        logger.info(failure.getMessage());
        if (logger.isDebugEnabled()) {
          logger.debug("Failed to write " + message, failure);
        }
        throw failure;
      }
    } finally {
      ctx.getPipeline().remove(NettyConstants.HEARTBEAT_HANDLER);
    }

    super.messageReceived(ctx, e);
  }
Example #16
0
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   myAllOpenChannels.add(e.getChannel());
   super.channelOpen(ctx, e);
 }
 @Override
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   super.channelOpen(ctx, e);
   this.channelHandlerContext = ctx;
   serverHandler = ctx.getPipeline().get(ServerHandler.class);
 }
Example #18
0
 @Override
 public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   SocketLog.info("worker disconnect :" + ctx.getChannel().getRemoteAddress().toString());
   context.getMaster().workerDisconnectProcess(ctx.getChannel());
   super.channelDisconnected(ctx, e);
 }
 @Override
 public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception {
   transportServiceAdapter.sent(e.getWrittenAmount());
   super.writeComplete(ctx, e);
 }
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   closeFuture.setResult(FutureResult.createVoid());
   super.channelClosed(ctx, e);
 }
Example #21
0
 @Override
 public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
   LOG.info(
       "Connection to {} has been closed, channel = {}", client.getRemoteAddr(), e.getChannel());
   super.channelClosed(ctx, e);
 }
 /**
  * Overriden superclass method. Adds the newly created Channel to the default channel group and
  * calls the super class {@link #channelOpen(ChannelHandlerContext, ChannelStateEvent)} method
  *
  * @see
  *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelOpen(org.jboss.netty.channel.ChannelHandlerContext,
  *     org.jboss.netty.channel.ChannelStateEvent)
  */
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent event) throws Exception {
   super.channelOpen(ctx, event);
 }
 /**
  * Overriden superclass method. Adds the newly created Channel to the default channel group and
  * calls the super class {@link #channelOpen(ChannelHandlerContext, ChannelStateEvent)} method
  *
  * @see
  *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#channelOpen(org.jboss.netty.channel.ChannelHandlerContext,
  *     org.jboss.netty.channel.ChannelStateEvent)
  */
 public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent event) throws Exception {
   super.channelOpen(ctx, event);
   this.defaultChannelGroup.add(event.getChannel());
 }