public OutboundServiceResponse(HttpVersion version) {
   this.nettyResponse = new DefaultHttpResponse(version, OK);
   this.nettyResponse.setChunked(false);
   this.nettyResponse.setContent(ChannelBuffers.dynamicBuffer());
   this.headerWrapper = new NettyHeaderWrapper(this.nettyResponse);
   this.outputStream = new ChannelBufferOutputStream(this.nettyResponse.getContent());
 }
示例#2
0
 private ChannelBuffer getHelloMessageBuffer() {
   // OFHello, OF version 1, xid of 0, total of 8 bytes
   byte[] messageData = {0x1, 0x0, 0x0, 0x8, 0x0, 0x0, 0x0, 0x0};
   ChannelBuffer channelBuffer = ChannelBuffers.dynamicBuffer();
   channelBuffer.writeBytes(messageData);
   return channelBuffer;
 }
示例#3
0
 @Override
 public ChannelBuffer encode(CommandMessage message) {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   buffer.writeInt(message.getCommand());
   ChannelBufferUtils.writeCommandArguments(buffer, message.getArguments());
   return buffer;
 }
  @Override
  public AsyncIOWriter write(byte[] data, int offset, int length) throws IOException {

    if (channel.isOpen()) {
      pendingWrite.incrementAndGet();
      final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();

      ChannelBufferOutputStream c = new ChannelBufferOutputStream(buffer);

      if (headerWritten) {
        c.write(Integer.toHexString(length - offset).getBytes("UTF-8"));
        c.write(CHUNK_DELIMITER);
      }

      c.write(data, offset, length);
      if (headerWritten) {
        c.write(CHUNK_DELIMITER);
      }

      channel.write(c.buffer()).addListener(listener);
      byteWritten = true;
      lastWrite = System.currentTimeMillis();
    } else {
      logger.warn("Trying to write on a closed channel {}", channel);
    }
    headerWritten = true;
    return this;
  }
示例#5
0
 @Override
 public ChannelBuffer encode(LevelColorMessage message) throws IOException {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   ChannelBufferUtils.writeString(buffer, message.getType());
   buffer.writeInt(message.getValue());
   return buffer;
 }
  public void handler(Message msg, Channel inBoundChannel, ChannelBuffer cb) {
    if (ResultCode.RESULT_CODE_00.getCode().equals(msg.getResponseCode())) {
      TblMerchantPos merchantPos = ManageCacheService.findPos(msg.getTerminalIdentification());
      if (merchantPos == null) {
        byte[] allBytes = msg.toMessgeBytes();
        ChannelBuffer retCB = ChannelBuffers.dynamicBuffer();
        retCB.writeBytes(allBytes);
        inBoundChannel.write(retCB);
        isContinue = false;
        return;
      } else {
        if (ApplicationContent.MSG_TYPE_SALE_RESP.equals(msg.getMSGType())) {
          // 查原来交易。将原交易金额负给4域
          TblTransactionMessage tm =
              ApplicationContentSpringProvider.getInstance().getMessageService().findSelf(msg);
          if (tm != null) {
            msg.setBCDField(4, tm.getFldTransactionAmount());
          }
        }

        if (ApplicationContent.MSG_TYPE_REVERSAL_RESP.equals(msg.getMSGType())
            || ApplicationContent.MSG_TYPE_SALE_RESP.equals(msg.getMSGType())
            || ApplicationContent.MSG_TYPE_SALE_RESP.equals(msg.getMSGType())) {
          msg.setUnicertainAscField(62, merchantPos.getFldBatchNo());
        }

        String targetMac = DefaultMessageHandler.getMAC(msg);
        msg.setBCDField(64, targetMac);
      }
    }
  }
示例#7
0
 public ChannelBuffer getContent() {
   ChannelBuffer cb = ChannelBuffers.dynamicBuffer();
   for (Frame frame : frames) {
     cb.writeBytes(frame.getPayload(), frame.getFrameSize() - 12);
   }
   return cb;
 }
 @Override
 public ChannelBuffer getEncodedMessage() {
   ChannelBuffer encodedMessage = ChannelBuffers.dynamicBuffer();
   encodedMessage.writeBytes("Command: StatusList\n".getBytes(CharsetUtil.UTF_8));
   for (ExtensionStatus es : statuses) {
     encodedMessage.writeBytes(
         ("ExtensionStatus: "
                 + new StringBuilder()
                     .append(es.getExtension())
                     .append(" ")
                     .append(
                         es.getStatus() == null
                             ? DEFAULT_STATUS
                             : new StringBuilder()
                                 .append(es.getStatus())
                                 .append(" ")
                                 .append(this.dateFormat.format(es.getSince()))
                                 .toString())
                     .toString()
                 + "\n")
             .getBytes(CharsetUtil.UTF_8));
   }
   encodedMessage.writeBytes("\n".getBytes(CharsetUtil.UTF_8));
   encodedMessage = encodedMessage.slice(0, encodedMessage.writerIndex());
   return encodedMessage;
 }
示例#9
0
  /** This test case checks BGP Keepalive message. */
  @Test
  public void keepaliveMessageTest1() throws BgpParseException {

    // BGP KEEPALIVE Message
    byte[] keepaliveMsg =
        new byte[] {
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          (byte) 0xff,
          0x00,
          0x13,
          0x04
        };

    byte[] testKeepaliveMsg;
    ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
    buffer.writeBytes(keepaliveMsg);

    BgpMessageReader<BgpMessage> reader = BgpFactories.getGenericReader();
    BgpMessage message;
    BgpHeader bgpHeader = new BgpHeader();

    message = reader.readFrom(buffer, bgpHeader);

    assertThat(message, instanceOf(BgpKeepaliveMsg.class));
    ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
    message.writeTo(buf);

    int readLen = buf.writerIndex();
    testKeepaliveMsg = new byte[readLen];
    buf.readBytes(testKeepaliveMsg, 0, readLen);

    assertThat(testKeepaliveMsg, is(keepaliveMsg));
  }
示例#10
0
文件: Server.java 项目: Analect/neo4j
 private ChunkingChannelBuffer newChunkingBuffer(Channel channel) {
   return new ChunkingChannelBuffer(
       ChannelBuffers.dynamicBuffer(),
       channel,
       chunkSize,
       getInternalProtocolVersion(),
       applicationProtocolVersion);
 }
示例#11
0
 @Override
 public ChannelBuffer encode(PlayerListMessage message) throws IOException {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   ChannelBufferUtils.writeString(buffer, message.getPlayerName());
   buffer.writeByte(message.playerIsOnline() ? 1 : 0);
   buffer.writeShort(message.getPing());
   return buffer;
 }
 /**
  * @param ctx
  * @return
  */
 protected ChannelBuffer cumulation(ChannelHandlerContext ctx) {
   ChannelBuffer c = cumulation;
   if (c == null) {
     c = ChannelBuffers.dynamicBuffer(ctx.getChannel().getConfig().getBufferFactory());
     cumulation = c;
   }
   return c;
 }
示例#13
0
 @Override
 public ChannelBuffer encode(OpenWindowMessage message) throws IOException {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   buffer.writeByte(message.getId());
   buffer.writeByte(message.getType());
   ChannelBufferUtils.writeString(buffer, message.getTitle());
   buffer.writeByte(message.getSlots());
   return buffer;
 }
 @Override
 protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
   ByteArrayOutputStream o = new ByteArrayOutputStream();
   new Packer(o).pack(msg);
   byte[] b = o.toByteArray();
   ChannelBuffer buf = ChannelBuffers.dynamicBuffer();
   buf.writeBytes(b);
   return buf;
 }
示例#15
0
 @Override
 public ChannelBuffer encode(RespawnMessage message) throws IOException {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   buffer.writeInt(message.getDimension());
   buffer.writeByte(message.getDifficulty());
   buffer.writeByte(message.getGameMode());
   buffer.writeShort(ChannelBufferUtils.getShifts(message.getWorldHeight()) - 1);
   ChannelBufferUtils.writeString(buffer, message.getWorldType());
   return buffer;
 }
 @Override
 public ChannelBuffer encode(EncryptionKeyRequestMessage message) {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   ChannelBufferUtils.writeString(buffer, message.getSessionId());
   byte[] publicKey = message.getSecretArray();
   buffer.writeShort((short) publicKey.length);
   buffer.writeBytes(publicKey);
   buffer.writeShort((short) message.getVerifyTokenArray().length);
   buffer.writeBytes(message.getVerifyTokenArray());
   return buffer;
 }
 @Override
 public ChannelBuffer encode(UnregisterPluginChannelMessage message) {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   for (Iterator<String> i = message.getTypes().iterator(); i.hasNext(); ) {
     buffer.writeBytes(i.next().getBytes(ChannelBufferUtils.CHARSET_UTF8));
     if (i.hasNext()) {
       buffer.writeByte(0);
     }
   }
   return buffer;
 }
示例#18
0
 @Override
 public ChannelBuffer encode(WindowClickMessage message) throws IOException {
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   buffer.writeByte(message.getWindowInstanceId());
   buffer.writeShort(message.getSlot());
   buffer.writeByte(message.isRightClick() ? 1 : 0);
   buffer.writeShort(message.getTransaction());
   buffer.writeByte(message.isShift() ? 1 : 0);
   ChannelBufferUtils.writeItemStack(buffer, message.getItem());
   return buffer;
 }
示例#19
0
 /**
  * Create a new Buffer from a Netty {@code ChannelBuffer} instance. Please use the static {@code
  * createXXX methods} to create Buffer instances.
  *
  * <p>This method is meant for internal use only.
  */
 public Buffer(ChannelBuffer buffer) {
   if (buffer instanceof DynamicChannelBuffer) {
     this.buffer = (DynamicChannelBuffer) buffer;
   } else {
     // TODO - if Netty could provide a DynamicChannelBuffer constructor which took a HeapBuffer
     // this would
     // save an extra copy
     this.buffer = (DynamicChannelBuffer) ChannelBuffers.dynamicBuffer(buffer.readableBytes());
     this.buffer.writeBytes(buffer, 0, buffer.readableBytes());
   }
 }
  public byte[] encode(Map<String, Object> value) throws ProtocolException {
    ChannelBuffer cb = ChannelBuffers.dynamicBuffer(100);
    encode(value, cb);

    int writeIndex = cb.writerIndex();
    byte[] result = new byte[writeIndex];

    cb.readBytes(result);

    return result;
  }
示例#21
0
  /*
   * (non-Javadoc)
   *
   * @see
   * org.jboss.netty.handler.codec.oneone.OneToOneEncoder#encode(org.jboss
   * .netty.channel.ChannelHandlerContext, org.jboss.netty.channel.Channel,
   * java.lang.Object)
   */
  @Override
  protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (!(msg instanceof Message)) return msg;
    Message message = (Message) msg;
    long commandId = ((Long) message.getHeader().getCommandId()).longValue();
    if (commandId != packetType.getCommandId()) return msg;

    DeliverRequestMessage requestMessage = (DeliverRequestMessage) message;

    ChannelBuffer bodyBuffer = ChannelBuffers.dynamicBuffer();

    bodyBuffer.writeBytes(
        Bytes.ensureCapacity(
            requestMessage.getUsernumber().getBytes(GlobalVars.defaultTransportCharset),
            DeliverRequest.USERNUMBER.getLength(),
            0));
    bodyBuffer.writeBytes(
        Bytes.ensureCapacity(
            requestMessage.getSpnumber().getBytes(GlobalVars.defaultTransportCharset),
            DeliverRequest.SPNUMBER.getLength(),
            0));
    bodyBuffer.writeByte(requestMessage.getTppid());
    bodyBuffer.writeByte(requestMessage.getTpudhi());
    bodyBuffer.writeByte(requestMessage.getMessagecoding());
    bodyBuffer.writeInt((int) requestMessage.getMessagelength());
    bodyBuffer.writeBytes(requestMessage.getMsgContentBytes());
    bodyBuffer.writeBytes(
        Bytes.ensureCapacity(
            requestMessage.getReserve().getBytes(GlobalVars.defaultTransportCharset),
            DeliverRequest.RESERVE.getLength(),
            0));

    requestMessage.setBodyBuffer(bodyBuffer.copy().array());

    ChannelBuffer msgBuffer = ChannelBuffers.dynamicBuffer();

    msgBuffer.writeBytes(requestMessage.getHeader().getHeadBuffer());
    msgBuffer.writeBytes(requestMessage.getBodyBuffer());

    return msgBuffer;
  }
示例#22
0
文件: Server.java 项目: Analect/neo4j
  protected void handleRequest(ChannelBuffer buffer, final Channel channel) {
    Byte continuation = readContinuationHeader(buffer, channel);
    if (continuation == null) {
      return;
    }
    if (continuation == ChunkingChannelBuffer.CONTINUATION_MORE) {
      PartialRequest partialRequest = partialRequests.get(channel);
      if (partialRequest == null) {
        // This is the first chunk in a multi-chunk request
        RequestType<T> type = getRequestContext(buffer.readByte());
        RequestContext context = readContext(buffer);
        ChannelBuffer targetBuffer = mapSlave(channel, context);
        partialRequest = new PartialRequest(type, context, targetBuffer);
        partialRequests.put(channel, partialRequest);
      }
      partialRequest.add(buffer);
    } else {
      PartialRequest partialRequest = partialRequests.remove(channel);
      RequestType<T> type;
      RequestContext context;
      ChannelBuffer targetBuffer;
      ChannelBuffer bufferToReadFrom;
      ChannelBuffer bufferToWriteTo;
      if (partialRequest == null) {
        // This is the one and single chunk in the request
        type = getRequestContext(buffer.readByte());
        context = readContext(buffer);
        targetBuffer = mapSlave(channel, context);
        bufferToReadFrom = buffer;
        bufferToWriteTo = targetBuffer;
      } else {
        // This is the last chunk in a multi-chunk request
        type = partialRequest.type;
        context = partialRequest.context;
        targetBuffer = partialRequest.buffer;
        partialRequest.add(buffer);
        bufferToReadFrom = targetBuffer;
        bufferToWriteTo = ChannelBuffers.dynamicBuffer();
      }

      bufferToWriteTo.clear();
      final ChunkingChannelBuffer chunkingBuffer =
          new ChunkingChannelBuffer(
              bufferToWriteTo,
              channel,
              chunkSize,
              getInternalProtocolVersion(),
              applicationProtocolVersion);
      submitSilent(
          targetCallExecutor,
          targetCaller(type, channel, context, chunkingBuffer, bufferToReadFrom));
    }
  }
示例#23
0
 public NettyHttpResponse(
     ChannelHandlerContext ctx,
     HttpResponse response,
     boolean isKeepAlive,
     Thread.UncaughtExceptionHandler exceptionHandler) {
   this.ctx = ctx;
   this.response = response;
   this.isKeepAlive = isKeepAlive;
   this.exceptionHandler = exceptionHandler;
   this.charset = DEFAULT_CHARSET;
   responseBuffer = ChannelBuffers.dynamicBuffer();
 }
 @Override
 public ChannelBuffer getEncodedMessage() {
   ChannelBuffer encodedMessage = ChannelBuffers.dynamicBuffer();
   encodedMessage.writeBytes("Command: Error\n".getBytes(CharsetUtil.UTF_8));
   encodedMessage.writeBytes(("Number: 5\n").getBytes(CharsetUtil.UTF_8));
   encodedMessage.writeBytes(
       ("Description: The register request failed as the extn is already in use\n")
           .getBytes(CharsetUtil.UTF_8));
   encodedMessage.writeBytes("\n".getBytes(CharsetUtil.UTF_8));
   encodedMessage = encodedMessage.slice(0, encodedMessage.writerIndex());
   return encodedMessage;
 }
  /* (non-Javadoc)
   * @see org.jboss.netty.handler.codec.oneone.OneToOneEncoder#encode(org.jboss.netty.channel.ChannelHandlerContext, org.jboss.netty.channel.Channel, java.lang.Object)
   */
  @Override
  protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception {
    if (!(msg instanceof Message)) return msg;

    Message message = (Message) msg;

    long commandId = ((Long) message.getHeader().getCommandId()).longValue();
    if (commandId != packetType.getCommandId()) return msg;

    CmppDeliverResponseMessage responseMessage = (CmppDeliverResponseMessage) msg;

    ChannelBuffer bodyBuffer = ChannelBuffers.dynamicBuffer();
    bodyBuffer.writeBytes(DefaultMsgIdUtil.msgId2Bytes(responseMessage.getMsgId()));
    bodyBuffer.writeInt((int) responseMessage.getResult());

    message.setBodyBuffer(bodyBuffer.copy().array());

    ChannelBuffer messageBuffer = ChannelBuffers.dynamicBuffer();
    messageBuffer.writeBytes(message.getHeader().getHeadBuffer());
    messageBuffer.writeBytes(message.getBodyBuffer());
    return messageBuffer;
  }
 void _close() {
   if (!isClosed.getAndSet(true)) {
     headerWritten = false;
     final ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
     ChannelBufferOutputStream c = new ChannelBufferOutputStream(buffer);
     try {
       c.write(ENDCHUNK);
       channel.write(buffer).addListener(ChannelFutureListener.CLOSE);
     } catch (IOException e) {
       logger.trace("Close error", e);
     }
   }
 }
 @Override
 public ChannelBuffer encodeToServer(PlayerLoginRequestMessage message) {
   PlayerLoginRequestMessage server = message;
   ChannelBuffer buffer = ChannelBuffers.dynamicBuffer();
   buffer.writeInt(server.getId());
   ChannelBufferUtils.writeString(buffer, server.getWorldType());
   buffer.writeByte(server.getGameMode());
   buffer.writeByte(server.getDimension());
   buffer.writeByte(server.getDifficulty());
   buffer.writeByte(0);
   buffer.writeByte(server.getMaxPlayers());
   return buffer;
 }
  /**
   * 自动缩小超长的帧数据缓存
   *
   * @param ctx
   * @return
   */
  protected void shrinkCumulation(ChannelHandlerContext ctx) {
    ChannelBuffer c = cumulation;
    if (this.cumulation != null) {
      if (cumulation.readableBytes() < this.minShrinkCapacity
          && cumulation.capacity() > this.minShrinkCapacity) {
        c =
            ChannelBuffers.dynamicBuffer(
                this.minShrinkCapacity, ctx.getChannel().getConfig().getBufferFactory());
        c.writeBytes(cumulation);

        this.cumulation = c;
      }
    }
  }
示例#29
0
 private void sendByteArray(ChannelHandlerContext ctx, byte[] buffer) {
   try {
     Channel channel = ctx.getChannel();
     ChannelFuture future = Channels.future(ctx.getChannel());
     ChannelBuffer b = ChannelBuffers.dynamicBuffer();
     // first send encoded key bytes size
     b.writeInt(buffer.length);
     // then the public key
     b.writeBytes(buffer);
     Channels.write(ctx, future, b);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  private Object processSingle(Channel channel, ChannelBuffer buf) {
    ParseResult result = parsePosition(buf);

    ChannelBuffer response = ChannelBuffers.dynamicBuffer(ByteOrder.LITTLE_ENDIAN, 8);
    response.writeBytes(ChannelBuffers.copiedBuffer(ByteOrder.LITTLE_ENDIAN, "*<T", CHARSET));
    response.writeInt((int) result.getId());
    sendReply(channel, response);

    if (result.getPosition().getFixTime() == null) {
      return null;
    }

    return result.getPosition();
  }