@Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {

    Object m = e.getMessage();
    if (!(m instanceof ChannelBuffer)) {
      ctx.sendUpstream(e);
      return;
    }

    ChannelBuffer input = (ChannelBuffer) m;
    if (!input.readable()) {
      return;
    }

    ChannelBuffer cumulation = cumulation(ctx);
    if (cumulation.readable()) {
      cumulation.discardReadBytes();
      cumulation.writeBytes(input);
      callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress());
    } else {
      callDecode(ctx, e.getChannel(), input, e.getRemoteAddress());
      if (input.readable()) {
        cumulation.writeBytes(input);
      }
    }
  }
  public static void send(MessageEvent event, Integer transactionId, Long connectionId)
      throws Exception {
    logger.debug("ConnectionResponse::send to " + event.getRemoteAddress());

    ChannelBuffer responseBuffer = ChannelBuffers.buffer(4 + 4 + 8);
    responseBuffer.writeInt(Action.CONNECT.getId());
    responseBuffer.writeInt(transactionId);
    responseBuffer.writeLong(connectionId);

    logger.debug("ConnectionResponse DUMP: " + Utils.getHexString(responseBuffer.array()));

    event.getChannel().write(responseBuffer, event.getRemoteAddress());
  }
Пример #3
0
  /* (non-Javadoc)
   * @see org.jboss.netty.channel.SimpleChannelHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
   */
  @Override
  public void messageReceived(final ChannelHandlerContext context, final MessageEvent e)
      throws Exception {
    String decoded;
    synchronized (stringWriter) {

      // extract the buffer from the message event
      final Object message = e.getMessage();
      if (!(message instanceof ChannelBuffer)) {
        context.sendUpstream(e);
        return;
      }
      final ChannelBuffer buffer = (ChannelBuffer) message;
      if (!buffer.readable()) {
        return;
      }

      // read all bytes from the buffer to the decoder stream
      final byte[] bytes = new byte[buffer.readableBytes()];
      buffer.readBytes(bytes);
      writerOutputStream.write(bytes);
      writerOutputStream.flush();
      decoded = stringWriter.toString();
      stringWriter.getBuffer().setLength(0);
    }

    // push all successfully decoded characters upstream
    Channels.fireMessageReceived(context, decoded, e.getRemoteAddress());
  }
Пример #4
0
 /**
  * {@inheritDoc}
  *
  * @see
  *     org.jboss.netty.channel.SimpleChannelUpstreamHandler#messageReceived(org.jboss.netty.channel.ChannelHandlerContext,
  *     org.jboss.netty.channel.MessageEvent)
  */
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   final SocketAddress remote = e.getRemoteAddress();
   ChannelBuffer buff = (ChannelBuffer) e.getMessage();
   if (buff.equals(BYE_BUFF)) {
     e.getChannel()
         .write(BYE_MSG, remote)
         .addListener(
             new ChannelFutureListener() {
               @Override
               public void operationComplete(ChannelFuture future) throws Exception {
                 future.getChannel().close();
               }
             });
     return;
   }
   e.getChannel()
       .write(e.getMessage(), remote)
       .addListener(
           new ChannelFutureListener() {
             @Override
             public void operationComplete(ChannelFuture future) throws Exception {
               if (future.isSuccess()) {
                 logger.info(" S:OK");
               } else {
                 logger.info(" S:FAILED");
               }
             }
           });
 }
  private void handleIncomingConfirmableCoapResponse(ChannelHandlerContext ctx, MessageEvent me) {
    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();
    CoapResponse coapResponse = (CoapResponse) me.getMessage();

    writeEmptyAcknowledgement(remoteEndpoint, coapResponse.getMessageID());

    ctx.sendUpstream(me);
  }
  public static void send(
      MessageEvent event, Integer transactionId, List<TorrentStats> torrentStatsList)
      throws Exception {
    logger.debug("ScrapeResponse::send to " + event.getRemoteAddress());

    ChannelBuffer responseBuffer = ChannelBuffers.buffer(4 + 4 + torrentStatsList.size() * 12);
    responseBuffer.writeInt(Action.SCRAPE.getId());
    responseBuffer.writeInt(transactionId);

    for (TorrentStats torrentStats : torrentStatsList) {
      responseBuffer.writeInt(torrentStats.seeders);
      responseBuffer.writeInt(torrentStats.completed);
      responseBuffer.writeInt(torrentStats.leechers);
    }

    logger.debug("ScrapeResponse DUMP: " + Utils.getHexString(responseBuffer.array()));

    event.getChannel().write(responseBuffer, event.getRemoteAddress());
  }
  private void handleIncomingConfirmableCoapRequest(ChannelHandlerContext ctx, MessageEvent me) {
    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();
    CoapMessage coapMessage = (CoapMessage) me.getMessage();

    IncomingReliableMessageExchange newMessageExchange =
        new IncomingReliableMessageExchange(remoteEndpoint, coapMessage.getMessageID());

    IncomingMessageExchange oldMessageExchange =
        ongoingMessageExchanges.get(remoteEndpoint, coapMessage.getMessageID());

    // Check if there is an ongoing
    if (oldMessageExchange != null) {

      if (oldMessageExchange instanceof IncomingReliableMessageExchange) {

        // if the old message exchange is reliable and the empty ACK was already sent send another
        // empty ACK
        if (((IncomingReliableMessageExchange) oldMessageExchange).isAcknowledgementSent())
          writeEmptyAcknowledgement(remoteEndpoint, coapMessage.getMessageID());

      }

      // if the old message was unreliable and the duplicate message is confirmable send empty ACK
      else writeEmptyAcknowledgement(remoteEndpoint, coapMessage.getMessageID());

      // As the message is already being processed there is nothing more to do
      return;
    }

    // try to add new reliable message exchange
    boolean added = false;
    synchronized (monitor) {
      Long time = System.currentTimeMillis() + MIN_EMPTY_ACK_DELAY_MILLIS;

      // Add message exchange to set of ongoing exchanges to detect duplicates
      if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) {
        ongoingMessageExchanges.put(remoteEndpoint, coapMessage.getMessageID(), newMessageExchange);
        added = true;
      }

      // If the scheduling of the empty ACK does not work then it was already scheduled
      if (!emptyAcknowledgementSchedule.put(time, newMessageExchange)) {
        log.error("Could not schedule empty ACK for message: {}", coapMessage);
        ongoingMessageExchanges.remove(remoteEndpoint, coapMessage.getMessageID());
        added = false;
      }
    }

    // everything is fine, so further process message
    if (added) ctx.sendUpstream(me);
  }
Пример #8
0
  @Override
  public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    HttpRequest request = (HttpRequest) e.getMessage();

    if (request.getContent().readableBytes() == 0) {
      BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected.");
      return;
    }

    transportMetrics.messagesReceived.mark();
    transportMetrics.messagesReceivedSize.update(request.getContent().readableBytes());

    // logger.debug("Received {}", request.getContent().toString(CharsetUtil.UTF_8));

    String contentTypeHeader = request.getHeader(CONTENT_TYPE);
    if (contentTypeHeader == null) {
      contentTypeHeader = BaseTransport.CONTENT_TYPE_PLAIN;
    }

    String decodedContent;
    if (BaseTransport.CONTENT_TYPE_FORM.equals(contentTypeHeader)) {
      QueryStringDecoder decoder =
          new QueryStringDecoder("?" + request.getContent().toString(CharsetUtil.UTF_8));
      List<String> d = decoder.getParameters().get("d");
      if (d == null) {
        BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected.");
        return;
      }
      decodedContent = d.get(0);
    } else {
      decodedContent = request.getContent().toString(CharsetUtil.UTF_8);
    }

    if (decodedContent.length() == 0) {
      BaseTransport.respond(e.getChannel(), INTERNAL_SERVER_ERROR, "Payload expected.");
      return;
    }

    String[] messages = MAPPER.readValue(decodedContent, String[].class);
    for (String message : messages) {
      SockJsMessage jsMessage = new SockJsMessage(message);
      ctx.sendUpstream(new UpstreamMessageEvent(e.getChannel(), jsMessage, e.getRemoteAddress()));
    }

    if (isJsonpEnabled) {
      BaseTransport.respond(e.getChannel(), OK, "ok");
    } else {
      BaseTransport.respond(e.getChannel(), NO_CONTENT, "");
    }
  }
Пример #9
0
 static MessageEvent consolidateComposite(MessageEvent e) {
   // Convert a composite buffer into a simple buffer to save memory
   // bandwidth on full write buffer.
   // This method should be eliminated once gathering write works.
   Object m = e.getMessage();
   if (m instanceof CompositeChannelBuffer) {
     e =
         new DownstreamMessageEvent(
             e.getChannel(),
             e.getFuture(),
             ((CompositeChannelBuffer) m).copy(),
             e.getRemoteAddress());
   }
   return e;
 }
  private void handleIncomingConfirmableCoapMessage(ChannelHandlerContext ctx, MessageEvent me) {

    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();
    CoapMessage coapMessage = (CoapMessage) me.getMessage();

    // Empty CON messages can be used as application layer PING (is CoAP endpoints alive?)
    if (coapMessage.getMessageCodeName() == MessageCode.Name.EMPTY)
      writeReset(remoteEndpoint, coapMessage.getMessageID());
    else if (MessageCode.isResponse(coapMessage.getMessageCode()))
      handleIncomingConfirmableCoapResponse(ctx, me);
    else if (MessageCode.isRequest(coapMessage.getMessageCode()))
      handleIncomingConfirmableCoapRequest(ctx, me);
    else
      log.error("Incoming CoAP message is neither empty nor request nor response: ", coapMessage);
  }
Пример #11
0
    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {

      ChannelBuffer buf = (ChannelBuffer) e.getMessage();

      while (buf.readable()) {

        char c = ((char) buf.readByte());

        if (c == ';') {

          processNotification(
              queueArn.toString(),
              e.getRemoteAddress() != null ? e.getRemoteAddress().toString() : "");

          // start reading new message

          queueArn = new StringBuffer("");

        } else {
          queueArn.append(c);
        }
      }
    }
Пример #12
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
   if (e.getMessage() instanceof Pressluft) {
     Pressluft prsslft = ((Pressluft) e.getMessage());
     switch (prsslft.getType()) {
       case QUERY:
         handleQuery(Query.fromByteArray(prsslft.getPayload()), e.getChannel());
         break;
       case RESULT:
         handleResult(Result.fromByteArray(prsslft.getPayload()), e.getRemoteAddress());
         break;
       default:
         logger.error("can not handle pressluft : " + prsslft.getType());
         break;
     }
   }
 }
  /**
   * If the incoming message is a confirmable {@link CoapRequest} it schedules the sending of an
   * empty acknowledgement to the sender if there wasn't a piggy-backed response within a period of
   * 2 seconds.
   *
   * <p>If the incoming message is a confirmable {@link CoapResponse} it immediately sends a proper
   * acknowledgement if there was an open request waiting for a seperate response or
   * update-notification. It immediately sends an RST if there was no such response expected.
   *
   * @param ctx The {@link ChannelHandlerContext} relating this handler (which implements the {@link
   *     ChannelUpstreamHandler} interface) to the datagramChannel that received the message.
   * @param me the {@link MessageEvent} containing the actual message
   * @throws Exception if an error occured
   */
  @Override
  public void messageReceived(final ChannelHandlerContext ctx, MessageEvent me) throws Exception {
    log.debug("Upstream from {}: {}.", me.getRemoteAddress(), me.getMessage());

    if (isShutdown()) return;

    if (me.getMessage() instanceof CoapMessage) {

      CoapMessage coapMessage = (CoapMessage) me.getMessage();

      if (coapMessage.getMessageTypeName() == MessageType.Name.CON)
        handleIncomingConfirmableCoapMessage(ctx, me);
      else if (coapMessage.getMessageTypeName() == MessageType.Name.NON)
        handleIncomingNonConfirmableMessage(ctx, me);
      else ctx.sendUpstream(me);
    } else ctx.sendUpstream(me);
  }
Пример #14
0
  /* (non-Javadoc)
   * @see org.jboss.netty.channel.SimpleChannelHandler#writeRequested(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.MessageEvent)
   */
  @Override
  public void writeRequested(final ChannelHandlerContext context, final MessageEvent e)
      throws Exception {

    // extract the string from the message event
    final Object message = e.getMessage();
    if (!(message instanceof String)) {
      context.sendDownstream(e);
      return;
    }
    String string = (String) message;

    // encode the string into a buffer
    ByteOrder byteOrder = context.getChannel().getConfig().getBufferFactory().getDefaultOrder();
    ChannelBuffer buffer = copiedBuffer(byteOrder, string, Charset.forName("utf-8"));

    // send the buffer downstream
    Channels.write(context, e.getFuture(), buffer, e.getRemoteAddress());
  }
 @Override
 public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception {
   if (e instanceof MessageEvent) {
     MessageEvent event = (MessageEvent) e;
     ChannelBuffer buffer = (ChannelBuffer) event.getMessage();
     while (buffer.readableBytes() > 0) {
       ChannelBuffer newBuffer = ChannelBuffers.dynamicBuffer();
       if (buffer.readableBytes() >= chunkSize) {
         newBuffer.writeBytes(buffer.readBytes(chunkSize));
       } else {
         newBuffer.writeBytes(buffer.readBytes(buffer.readableBytes()));
       }
       Thread.sleep(latency);
       write(ctx, e.getFuture(), newBuffer, event.getRemoteAddress());
     }
   } else {
     ctx.sendDownstream(e);
   }
 }
  @Override
  public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent evt) throws Exception {
    if (!(evt instanceof MessageEvent)) {
      ctx.sendDownstream(evt);
      return;
    }

    MessageEvent e = (MessageEvent) evt;
    Object originalMessage = e.getMessage();

    if (originalMessage instanceof ChannelBuffer) {
      // 对于ChannelBuffer不尝试编码
      ctx.sendDownstream(evt);
    } else {
      ChannelBuffer encodedMessage = encode(ctx, e.getChannel(), originalMessage);
      if (encodedMessage != null) {
        Channels.write(ctx, e.getFuture(), encodedMessage, e.getRemoteAddress());
      }
    }
  }
  private void handleOutgoingCoapResponse(ChannelHandlerContext ctx, MessageEvent me) {

    CoapResponse coapResponse = (CoapResponse) me.getMessage();
    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();

    IncomingMessageExchange messageExchange;
    synchronized (monitor) {
      messageExchange = ongoingMessageExchanges.remove(remoteEndpoint, coapResponse.getMessageID());
    }

    if (messageExchange instanceof IncomingReliableMessageExchange) {

      // if the ongoing message exchange is reliable and the empty ACK was not yet sent make
      // response piggy-
      // backed and suppress scheduled empty ACK
      if (!((IncomingReliableMessageExchange) messageExchange).isAcknowledgementSent()) {
        coapResponse.setMessageType(MessageType.Name.ACK.getNumber());
        ((IncomingReliableMessageExchange) messageExchange).setAcknowledgementSent();
      }
    }

    ctx.sendDownstream(me);
  }
 @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);
   }
 }
Пример #19
0
 public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
   OioDatagramChannel channel = (OioDatagramChannel) e.getChannel();
   ChannelFuture future = e.getFuture();
   if (e instanceof ChannelStateEvent) {
     ChannelStateEvent stateEvent = (ChannelStateEvent) e;
     ChannelState state = stateEvent.getState();
     Object value = stateEvent.getValue();
     switch (state) {
       case OPEN:
         if (Boolean.FALSE.equals(value)) {
           OioDatagramWorker.close(channel, future);
         }
         break;
       case BOUND:
         if (value != null) {
           bind(channel, future, (SocketAddress) value);
         } else {
           OioDatagramWorker.close(channel, future);
         }
         break;
       case CONNECTED:
         if (value != null) {
           connect(channel, future, (SocketAddress) value);
         } else {
           OioDatagramWorker.disconnect(channel, future);
         }
         break;
       case INTEREST_OPS:
         OioDatagramWorker.setInterestOps(channel, future, ((Integer) value).intValue());
         break;
     }
   } else if (e instanceof MessageEvent) {
     MessageEvent evt = (MessageEvent) e;
     OioDatagramWorker.write(channel, future, evt.getMessage(), evt.getRemoteAddress());
   }
 }
  private void handleIncomingNonConfirmableMessage(ChannelHandlerContext ctx, MessageEvent me) {
    InetSocketAddress remoteEndpoint = (InetSocketAddress) me.getRemoteAddress();
    CoapMessage coapMessage = (CoapMessage) me.getMessage();

    boolean isDuplicate = true;

    if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) {
      IncomingMessageExchange messageExchange =
          new IncomingMessageExchange(remoteEndpoint, coapMessage.getMessageID());

      synchronized (monitor) {
        if (!ongoingMessageExchanges.contains(remoteEndpoint, coapMessage.getMessageID())) {
          ongoingMessageExchanges.put(remoteEndpoint, coapMessage.getMessageID(), messageExchange);

          isDuplicate = false;
        }
      }

      ctx.sendUpstream(me);
    }

    if (isDuplicate)
      log.info("Received duplicate (non-confirmable). IGNORE! (Message: {})", coapMessage);
  }
Пример #21
0
 @Override
 public void messageReceived(ChannelHandlerContext ctx, MessageEvent me) {
   log.info("Message received from {}", me.getRemoteAddress());
   ctx.sendUpstream(me);
 }
Пример #22
0
 @Override
 public void writeRequested(ChannelHandlerContext ctx, MessageEvent me) {
   log.info("Message to be sent to {}", me.getRemoteAddress());
   ctx.sendDownstream(me);
 }