/**
   *
   * <li>方法名:appendBytes
   * <li>@param datas
   * <li>返回类型:void
   * <li>说明:将数据放入到缓冲区中
   * <li>创建人:CshBBrain;技术博客:http://cshbbrain.iteye.com/
   * <li>创建日期:2012-9-19
   * <li>修改人:
   * <li>修改日期:
   */
  public void appendBytes(byte... datas) {
    this.isBuffered = true;
    ByteBuffer buffer = this.getBuffer();
    if (buffer.remaining() >= datas.length) { // 缓冲区的空间大于数据的长度
      buffer.put(datas);
      log.info("the postion of the data: " + buffer.position());
    } else { // 缓冲区的空间小于数据的长度
      int offset = 0; // 初始相对位移为0
      int length = buffer.remaining(); // 初始传递的数据长度为缓冲区的剩余长度

      do {
        buffer.put(datas, offset, length);
        offset += length;

        if (offset < datas.length) {
          buffer = this.getBuffer();
          length =
              (buffer.remaining() > (datas.length - offset)
                  ? (datas.length - offset)
                  : buffer.remaining());
        } else {
          break;
        }
      } while (true);
    }
  }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!isBigInteger(obj)) {
     return super.write(buff, obj);
   }
   BigInteger x = (BigInteger) obj;
   if (BigInteger.ZERO.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_0);
   } else if (BigInteger.ONE.equals(x)) {
     buff.put((byte) TAG_BIG_INTEGER_1);
   } else {
     int bits = x.bitLength();
     if (bits <= 63) {
       buff.put((byte) TAG_BIG_INTEGER_SMALL);
       DataUtils.writeVarLong(buff, x.longValue());
     } else {
       buff.put((byte) TYPE_BIG_INTEGER);
       byte[] bytes = x.toByteArray();
       DataUtils.writeVarInt(buff, bytes.length);
       buff = DataUtils.ensureCapacity(buff, bytes.length);
       buff.put(bytes);
     }
   }
   return buff;
 }
  public <RESPONSE extends ReaderResponse<?>> RESPONSE transmit(ReaderCommand<?, ?> readerCommand)
      throws Exception {

    Log.trace("Sending command: " + readerCommand.toString());

    // ACR122
    byte[] header = {(byte) 0xff, (byte) 0x00, (byte) 0x00, (byte) 0x00};
    out.put(header);
    out.put((byte) readerCommand.getLength());
    readerCommand.transfer(out);

    try {
      out.flip();
      CommandAPDU apdu = new CommandAPDU(out);
      ResponseAPDU resp = channel.transmit(apdu);
      out.clear();
      ByteBuffer in = ByteBuffer.wrap(resp.getBytes());
      // check response !!!

      RESPONSE response = (RESPONSE) readerCommand.receive(in);
      Log.trace("Receiving command: " + response.toString());
      return response;
    } catch (CardException e) {
      e.printStackTrace();
      throw new Exception(e.getMessage());
    }
  }
 /**
  * Send the given message to the given client. The message does not need to have the length of the
  * message prepended. It is not guaranteed the message will arrive, as it can't be determined if
  * writing on a closed connection (it could appear to work). This won't be known until later when
  * get a disconnected callback is made.
  *
  * @param channelKey the key of the client to which the message should be sent.
  * @param buffer the message to send.
  */
 public void write(SelectionKey channelKey, byte[] buffer) {
   short len = (short) buffer.length;
   byte[] lengthBytes = messageLength.lengthToBytes(len);
   // copying into byte buffer is actually faster than writing to channel twice over many (>10000)
   // runs
   ByteBuffer writeBuffer = ByteBuffer.allocate(len + lengthBytes.length);
   writeBuffer.put(lengthBytes);
   writeBuffer.put(buffer);
   writeBuffer.flip();
   if (buffer != null && state.get() == State.RUNNING) {
     int bytesWritten;
     try {
       // only 1 thread can write to a channel at a time
       SocketChannel channel = (SocketChannel) channelKey.channel();
       synchronized (channel) {
         bytesWritten = channel.write(writeBuffer);
       }
       if (bytesWritten == -1) {
         resetKey(channelKey);
         disconnected(channelKey);
       }
     } catch (Exception e) {
       resetKey(channelKey);
       disconnected(channelKey);
     }
   }
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!(obj instanceof Integer)) {
     return super.write(buff, obj);
   }
   int x = (Integer) obj;
   if (x < 0) {
     // -Integer.MIN_VALUE is smaller than 0
     if (-x < 0 || -x > DataUtils.COMPRESSED_VAR_INT_MAX) {
       buff.put((byte) TAG_INTEGER_FIXED);
       buff.putInt(x);
     } else {
       buff.put((byte) TAG_INTEGER_NEGATIVE);
       DataUtils.writeVarInt(buff, -x);
     }
   } else if (x <= 15) {
     buff.put((byte) (TAG_INTEGER_0_15 + x));
   } else if (x <= DataUtils.COMPRESSED_VAR_INT_MAX) {
     buff.put((byte) TYPE_INT);
     DataUtils.writeVarInt(buff, x);
   } else {
     buff.put((byte) TAG_INTEGER_FIXED);
     buff.putInt(x);
   }
   return buff;
 }
Exemple #6
0
  public static void putLength(ByteBuffer buf, int length, boolean masked) {
    if (length < 0) {
      throw new IllegalArgumentException("Length cannot be negative");
    }
    byte b = (masked ? (byte) 0x80 : 0x00);

    // write the uncompressed length
    if (length > 0xFF_FF) {
      buf.put((byte) (b | 0x7F));
      buf.put((byte) 0x00);
      buf.put((byte) 0x00);
      buf.put((byte) 0x00);
      buf.put((byte) 0x00);
      buf.put((byte) ((length >> 24) & 0xFF));
      buf.put((byte) ((length >> 16) & 0xFF));
      buf.put((byte) ((length >> 8) & 0xFF));
      buf.put((byte) (length & 0xFF));
    } else if (length >= 0x7E) {
      buf.put((byte) (b | 0x7E));
      buf.put((byte) (length >> 8));
      buf.put((byte) (length & 0xFF));
    } else {
      buf.put((byte) (b | length));
    }
  }
 ByteBuffer getMalformByteBuffer() throws UnsupportedEncodingException {
   ByteBuffer buffer = ByteBuffer.allocate(20);
   buffer.put((byte) 0xd8);
   buffer.put(unibytes);
   buffer.flip();
   return buffer;
 }
  @Override
  public ByteBuffer getTile(final int clipmapLevel, final Tile tile) throws Exception {
    final int tileX = tile.getX();
    final int tileY = tile.getY();

    final byte[] heightMap = maps.get(clipmapLevel);
    final int heightMapSize = heightMapSizes.get(clipmapLevel);

    final ByteBuffer data = tileDataPool.get();
    for (int y = 0; y < tileSize; y++) {
      for (int x = 0; x < tileSize; x++) {
        final int index = x + y * tileSize;

        final int heightX = tileX * tileSize + x;
        final int heightY = tileY * tileSize + y;
        if (heightX < 0 || heightX >= heightMapSize || heightY < 0 || heightY >= heightMapSize) {
          data.put(index * 3 + 0, (byte) 0);
          data.put(index * 3 + 1, (byte) 0);
          data.put(index * 3 + 2, (byte) 0);
        } else {
          data.put(index * 3 + 0, heightMap[3 * (heightY * heightMapSize + heightX) + 0]);
          data.put(index * 3 + 1, heightMap[3 * (heightY * heightMapSize + heightX) + 1]);
          data.put(index * 3 + 2, heightMap[3 * (heightY * heightMapSize + heightX) + 2]);
        }
      }
    }
    return data;
  }
  private boolean _send(String text) throws IOException {
    if (!this.handshakeComplete) {
      throw new NotYetConnectedException();
    }
    if (text == null) {
      throw new NullPointerException("Cannot send 'null' data to a WebSocket.");
    }

    // Get 'text' into a WebSocket "frame" of bytes
    byte[] textBytes = text.getBytes(UTF8_CHARSET.toString());
    ByteBuffer b = ByteBuffer.allocate(textBytes.length + 2);
    b.put(DATA_START_OF_FRAME);
    b.put(textBytes);
    b.put(DATA_END_OF_FRAME);
    b.rewind();

    // See if we have any backlog that needs to be sent first
    if (_write()) {
      // Write the ByteBuffer to the socket
      this.socketChannel.write(b);
    }

    // If we didn't get it all sent, add it to the buffer of buffers
    if (b.remaining() > 0) {
      if (!this.bufferQueue.offer(b)) {
        throw new IOException(
            "Buffers are full, message could not be sent to"
                + this.socketChannel.socket().getRemoteSocketAddress());
      }
      return false;
    }
    return true;
  }
  public String asHexToken(Key key) {
    try {
      Cipher encodingCipher = Cipher.getInstance("AES");
      encodingCipher.init(Cipher.ENCRYPT_MODE, key);

      ByteBuffer buffer = ByteBuffer.allocate(16 + 1 + 8 + 8 + getBufferSize());
      buffer.position(16);
      buffer.put(getId());
      buffer.putLong(getExpires().getTimeInMillis());
      buffer.putLong(getUoid());
      getBytes(buffer);
      if (buffer.position() != buffer.capacity()) {
        throw new RuntimeException(
            "Buffer's position should be at the end "
                + buffer.position()
                + "/"
                + buffer.capacity());
      }
      MessageDigest messageDigest = MessageDigest.getInstance("MD5");
      buffer.position(16);
      messageDigest.update(buffer);
      buffer.position(0);
      buffer.put(messageDigest.digest());

      byte[] encodedBytes = encodingCipher.doFinal(buffer.array());
      String encodedHexString = new String(Hex.encodeHex(encodedBytes));
      return encodedHexString;
    } catch (Exception e) {
      LOGGER.error("", e);
    }
    return null;
  }
Exemple #11
0
  protected void createWriteBuffer(ByteBuffer buf) {
    if (_primaryWriteBuffer == null) {
      _primaryWriteBuffer = _selectorThread.getPooledBuffer();
      _primaryWriteBuffer.put(buf);
    } else {
      ByteBuffer temp = _selectorThread.getPooledBuffer();
      temp.put(buf);

      int remaining = temp.remaining();
      _primaryWriteBuffer.flip();
      int limit = _primaryWriteBuffer.limit();

      if (remaining >= _primaryWriteBuffer.remaining()) {
        temp.put(_primaryWriteBuffer);
        _selectorThread.recycleBuffer(_primaryWriteBuffer);
        _primaryWriteBuffer = temp;
      } else {
        _primaryWriteBuffer.limit(remaining);
        temp.put(_primaryWriteBuffer);
        _primaryWriteBuffer.limit(limit);
        _primaryWriteBuffer.compact();
        _secondaryWriteBuffer = _primaryWriteBuffer;
        _primaryWriteBuffer = temp;
      }
    }
  }
Exemple #12
0
  @Override
  public byte[] packLog(long index, int itemsToPack) {
    if (index < this.startIndex.get() || index >= this.nextIndex.get()) {
      throw new IllegalArgumentException("index out of range");
    }

    try {
      ByteArrayOutputStream memoryStream = new ByteArrayOutputStream();
      GZIPOutputStream gzipStream = new GZIPOutputStream(memoryStream);
      PreparedStatement ps = this.connection.prepareStatement(SELECT_RANGE_SQL);
      ps.setLong(1, index);
      ps.setLong(2, index + itemsToPack);
      ResultSet rs = ps.executeQuery();
      while (rs.next()) {
        byte[] value = rs.getBytes(4);
        int size = value.length + Long.BYTES + 1 + Integer.BYTES;
        ByteBuffer buffer = ByteBuffer.allocate(size);
        buffer.putInt(size);
        buffer.putLong(rs.getLong(2));
        buffer.put(rs.getByte(3));
        buffer.put(value);
        gzipStream.write(buffer.array());
      }

      rs.close();
      gzipStream.flush();
      memoryStream.flush();
      gzipStream.close();
      return memoryStream.toByteArray();
    } catch (Throwable error) {
      this.logger.error("failed to pack log entries", error);
      throw new RuntimeException("log store error", error);
    }
  }
 public void putToBuffer(ByteBuffer buffer) {
   buffer.put(requestType.getCode());
   buffer.put(errorCode.getCode());
   buffer.putInt(sku);
   buffer.putShort(store);
   buffer.putInt(amount);
 }
  @Override
  public void format(AssociationMessage message, ByteBuffer bb) {
    if (null == message) {
      throw new IllegalStateException("No ApplicationMessage set");
    }
    setType(message.getType());

    ByteBuffer bbAppMessage = ByteBuffer.allocate(5000);
    message.format(bbAppMessage);
    presentationLength.setLength(
        bbAppMessage.position()
            + message.getPresentationHeader().length
            + message.getPresentationTrailer().length);
    length.setLength(
        presentationLength.getByteCount() + sessionLength() + presentationLength.getLength());
    bbAppMessage.flip();

    Bits.putUnsignedByte(bb, type.asShort());
    length.format(bb);

    LengthInformation li = new LengthInformation();

    for (ParameterIdentifier pi : parameterIdentifiers) {
      Bits.putUnsignedByte(bb, pi.id);
      li.setLength(pi.data.length);
      li.format(bb);
      bb.put(pi.data);
    }

    presentationLength.format(bb);
    bb.put(message.getPresentationHeader());
    bb.put(bbAppMessage);
    bb.put(message.getPresentationTrailer());
  }
  @Override
  public void write(SMPPlayer player, Server server, Object... obj) {
    if (obj.length >= 6) {
      ByteBuffer bb;

      if (obj[0] instanceof Integer
          && obj[1] instanceof Byte
          && obj[2] instanceof Byte
          && obj[3] instanceof Byte
          && obj[4] instanceof Byte
          && obj[5] instanceof Byte) {
        bb = ByteBuffer.allocate(10);

        bb.put(ID);
        bb.putInt((Integer) obj[0]);
        bb.put((Byte) obj[1]);
        bb.put((Byte) obj[2]);
        bb.put((Byte) obj[3]);
        bb.put((Byte) obj[4]);
        bb.put((Byte) obj[5]);

        try {
          player.writeData(bb.array());
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    }
  }
  private void _readFrame() throws UnsupportedEncodingException {
    byte newestByte = this.buffer.get();

    if (newestByte == DATA_START_OF_FRAME) { // Beginning of Frame
      this.currentFrame = null;

    } else if (newestByte == DATA_END_OF_FRAME) { // End of Frame
      String textFrame = null;
      // currentFrame will be null if END_OF_FRAME was send directly after
      // START_OF_FRAME, thus we will send 'null' as the sent message.
      if (this.currentFrame != null) {
        textFrame = new String(this.currentFrame.array(), UTF8_CHARSET.toString());
      }
      // fire onMessage method
      this.onMessage(textFrame);

    } else { // Regular frame data, add to current frame buffer
      ByteBuffer frame =
          ByteBuffer.allocate(
              (this.currentFrame != null ? this.currentFrame.capacity() : 0)
                  + this.buffer.capacity());
      if (this.currentFrame != null) {
        this.currentFrame.rewind();
        frame.put(this.currentFrame);
      }
      frame.put(newestByte);
      this.currentFrame = frame;
    }
  }
Exemple #17
0
  /**
   * Copies bytes from the channel buffer into a destination <tt>ByteBuffer</tt>
   *
   * @param dst A <tt>ByteBuffer</tt> to place the data in.
   * @return The number of bytes copied.
   */
  private final int copyBufferedBytes(ByteBuffer dst) {
    final int bytesToCopy = dst.remaining();

    if (ungotc != -1 && dst.hasRemaining()) {
      dst.put((byte) ungotc);
      ungotc = -1;
    }

    if (buffer.hasRemaining() && dst.hasRemaining()) {

      if (dst.remaining() >= buffer.remaining()) {
        //
        // Copy out any buffered bytes
        //
        dst.put(buffer);

      } else {
        //
        // Need to clamp source (buffer) size to avoid overrun
        //
        ByteBuffer tmp = buffer.duplicate();
        tmp.limit(tmp.position() + dst.remaining());
        dst.put(tmp);
        buffer.position(tmp.position());
      }
    }

    return bytesToCopy - dst.remaining();
  }
Exemple #18
0
 protected void doWrite(ByteBuffer out) {
   super.doWrite(out);
   if ((flags & 0x1) != 0) // self ref
   return;
   out.put(asciiString(type), 0, 4);
   out.putShort(recordSize);
   out.putShort(version);
   out.putShort(kind);
   NIOUtils.writePascalStringL(out, volumeName, 27);
   out.putInt(volumeCreateDate);
   out.putShort(volumeSignature);
   out.putShort(volumeType);
   out.putInt(parentDirId);
   NIOUtils.writePascalStringL(out, fileName, 63);
   out.putInt(fileNumber);
   out.putInt(createdLocalDate);
   out.put(asciiString(fileTypeName), 0, 4);
   out.put(asciiString(creatorName), 0, 4);
   out.putShort(nlvlFrom);
   out.putShort(nlvlTo);
   out.putInt(volumeAttributes);
   out.putShort(fsId);
   out.put(new byte[10]);
   for (ExtraField extraField : extra) {
     out.putShort(extraField.type);
     out.putShort((short) extraField.len);
     out.put(extraField.data);
   }
   out.putShort((short) -1);
   out.putShort((short) 0);
 }
  @Override
  public void append(Framedata nextframe) throws InvalidFrameException {
    ByteBuffer b = nextframe.getPayloadData();
    if (unmaskedpayload == null) {
      unmaskedpayload = ByteBuffer.allocate(b.remaining());
      b.mark();
      unmaskedpayload.put(b);
      b.reset();
    } else {
      b.mark();
      unmaskedpayload.position(unmaskedpayload.limit());
      unmaskedpayload.limit(unmaskedpayload.capacity());

      if (b.remaining() > unmaskedpayload.remaining()) {
        ByteBuffer tmp = ByteBuffer.allocate(b.remaining() + unmaskedpayload.capacity());
        unmaskedpayload.flip();
        tmp.put(unmaskedpayload);
        tmp.put(b);
        unmaskedpayload = tmp;

      } else {
        unmaskedpayload.put(b);
      }
      unmaskedpayload.rewind();
      b.reset();
    }
    fin = nextframe.isFin();
  }
Exemple #20
0
  public static String generateHallmark(String secretPhrase, String host, int weight, int date) {

    if (host.length() == 0 || host.length() > 100) {
      throw new IllegalArgumentException("Hostname length should be between 1 and 100");
    }
    if (weight <= 0 || weight > Constants.MAX_BALANCE_NXT) {
      throw new IllegalArgumentException(
          "Weight should be between 1 and " + Constants.MAX_BALANCE_NXT);
    }

    byte[] publicKey = Crypto.getPublicKey(secretPhrase);
    byte[] hostBytes = Convert.toBytes(host);

    ByteBuffer buffer = ByteBuffer.allocate(32 + 2 + hostBytes.length + 4 + 4 + 1);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(publicKey);
    buffer.putShort((short) hostBytes.length);
    buffer.put(hostBytes);
    buffer.putInt(weight);
    buffer.putInt(date);

    byte[] data = buffer.array();
    data[data.length - 1] = (byte) ThreadLocalRandom.current().nextInt();
    byte[] signature = Crypto.sign(data, secretPhrase);

    return Convert.toHexString(data) + Convert.toHexString(signature);
  }
 @Override
 public void compress(int[] in, IntWrapper inpos, int inlength, int[] out, IntWrapper outpos) {
   if (inlength == 0) return;
   int initoffset = 0;
   ByteBuffer buf = ByteBuffer.allocateDirect(inlength * 8);
   for (int k = inpos.get(); k < inpos.get() + inlength; ++k) {
     int val = in[k] - initoffset;
     initoffset = in[k];
     do {
       int b = (val & 127);
       val >>>= 7;
       if (val != 0) {
         b |= 128;
       }
       buf.put((byte) b);
     } while (val != 0);
   }
   while (buf.position() % 4 != 0) buf.put((byte) 128);
   final int length = buf.position();
   buf.flip();
   IntBuffer ibuf = buf.asIntBuffer();
   ibuf.get(out, outpos.get(), length / 4);
   outpos.add(length / 4);
   inpos.add(inlength);
 }
Exemple #22
0
 @Override
 public final void storeYCbCr(int x, int y, byte Y, byte Cb, byte Cr) {
   int i = ((height - y - 1) * width + x) * storageComponents;
   data.put(i++, Y);
   data.put(i++, Cb);
   data.put(i++, Cr);
 }
 protected final void afterDecodingKeyValue(
     DataInputStream source, ByteBuffer dest, HFileBlockDefaultDecodingContext decodingCtx)
     throws IOException {
   if (decodingCtx.getHFileContext().isIncludesTags()) {
     int tagsLength = ByteBufferUtils.readCompressedInt(source);
     // Put as unsigned short
     dest.put((byte) ((tagsLength >> 8) & 0xff));
     dest.put((byte) (tagsLength & 0xff));
     if (tagsLength > 0) {
       TagCompressionContext tagCompressionContext = decodingCtx.getTagCompressionContext();
       // When tag compression is been used in this file, tagCompressionContext will have a not
       // null value passed.
       if (tagCompressionContext != null) {
         tagCompressionContext.uncompressTags(source, dest, tagsLength);
       } else {
         ByteBufferUtils.copyFromStreamToBuffer(dest, source, tagsLength);
       }
     }
   }
   if (decodingCtx.getHFileContext().isIncludesMvcc()) {
     long memstoreTS = -1;
     try {
       // Copy memstore timestamp from the data input stream to the byte
       // buffer.
       memstoreTS = WritableUtils.readVLong(source);
       ByteBufferUtils.writeVLong(dest, memstoreTS);
     } catch (IOException ex) {
       throw new RuntimeException(
           "Unable to copy memstore timestamp " + memstoreTS + " after decoding a key/value");
     }
   }
 }
 private static byte[] createDALIMessage(int address, int action) {
   address = (address * 2) + 1;
   ByteBuffer byteBuffer = ByteBuffer.allocate(7);
   byteBuffer.put(new byte[] {(byte) DALI_START, 0x00, 0x00, 0x00, (byte) address, (byte) action});
   byteBuffer.put(checksum(byteBuffer));
   return byteBuffer.array();
 }
 @Override
 public ByteBuffer write(ByteBuffer buff, Object obj) {
   if (!(obj instanceof Long)) {
     return super.write(buff, obj);
   }
   long x = (Long) obj;
   if (x < 0) {
     // -Long.MIN_VALUE is smaller than 0
     if (-x < 0 || -x > DataUtils.COMPRESSED_VAR_LONG_MAX) {
       buff.put((byte) TAG_LONG_FIXED);
       buff.putLong(x);
     } else {
       buff.put((byte) TAG_LONG_NEGATIVE);
       DataUtils.writeVarLong(buff, -x);
     }
   } else if (x <= 7) {
     buff.put((byte) (TAG_LONG_0_7 + x));
   } else if (x <= DataUtils.COMPRESSED_VAR_LONG_MAX) {
     buff.put((byte) TYPE_LONG);
     DataUtils.writeVarLong(buff, x);
   } else {
     buff.put((byte) TAG_LONG_FIXED);
     buff.putLong(x);
   }
   return buff;
 }
  public void newCheckpoint(byte[] state, byte[] stateHash, int consensusId) {
    String ckpPath = DEFAULT_DIR + String.valueOf(id) + "." + System.currentTimeMillis() + ".tmp";
    try {
      checkpointLock.lock();
      RandomAccessFile ckp = new RandomAccessFile(ckpPath, (syncCkp ? "rwd" : "rw"));

      ByteBuffer bf = ByteBuffer.allocate(state.length + stateHash.length + 4 * INT_BYTE_SIZE);
      bf.putInt(state.length);
      bf.put(state);
      bf.putInt(stateHash.length);
      bf.put(stateHash);
      bf.putInt(EOF);
      bf.putInt(consensusId);

      byte[] ckpState = bf.array();

      ckp.write(ckpState);
      ckp.close();

      if (isToLog) deleteLogFile();
      deleteLastCkp();
      renameCkp(ckpPath);
      if (isToLog) createLogFile();

    } catch (FileNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } finally {
      checkpointLock.unlock();
    }
  }
Exemple #27
0
 @Override
 void putMyBytes(ByteBuffer buffer) {
   byte[] aliasBytes = Convert.toBytes(aliasName);
   buffer.put((byte) aliasBytes.length);
   buffer.put(aliasBytes);
   buffer.putLong(priceNQT);
 }
Exemple #28
0
  /** Preps the send buffer for next transmission */
  public void prepSendBuffer() {
    // sendBuffer.rewind();
    // Put the protocol ID and the localSequence
    sendBuffer.put(protocol);
    sendBuffer.putShort(localSequence);
    // Put analog values
    sendBuffer.putShort(controller.analogState.get(0));
    sendBuffer.putShort(controller.analogState.get(1));
    sendBuffer.putShort(controller.analogState.get(2));
    sendBuffer.putShort(controller.analogState.get(3));

    // Build first byte and put
    byte firstByte = 0;
    for (int n = 0; n < 7; n++, firstByte <<= 1) if (controller.buttonState.get(n)) firstByte |= 1;
    if (controller.buttonState.get(7)) firstByte |= 1;
    sendBuffer.put(firstByte);

    // Build second byte and put
    byte secondByte = 0;
    for (int n = 8; n < 15; n++, secondByte <<= 1)
      if (controller.buttonState.get(n)) secondByte |= 1;
    if (controller.buttonState.get(15)) secondByte |= 1;
    sendBuffer.put(secondByte);

    // Put the extra button (not implemented in touch yet)
    // sendBuffer.put((byte) (controller.buttons.get(16) ? 1 : 0));
    sendBuffer.rewind();
  }
 @Override
 public boolean serialize(final ByteBuffer buffer) {
   if (this.contents.size() > 65535) {
     return false;
   }
   buffer.putShort((short) this.contents.size());
   for (int i = 0; i < this.contents.size(); ++i) {
     final Content contents_element = this.contents.get(i);
     final boolean contents_element_ok = contents_element.serialize(buffer);
     if (!contents_element_ok) {
       return false;
     }
   }
   if (this.contentsSelection != null) {
     buffer.put((byte) 1);
     final boolean contentsSelection_ok = this.contentsSelection.serialize(buffer);
     if (!contentsSelection_ok) {
       return false;
     }
   } else {
     buffer.put((byte) 0);
   }
   if (this.buyableContents.size() > 65535) {
     return false;
   }
   buffer.putShort((short) this.buyableContents.size());
   for (int i = 0; i < this.buyableContents.size(); ++i) {
     final BuyableContent buyableContents_element = this.buyableContents.get(i);
     final boolean buyableContents_element_ok = buyableContents_element.serialize(buffer);
     if (!buyableContents_element_ok) {
       return false;
     }
   }
   return true;
 }
  @Override
  public byte[] getBytes() {
    ByteBuffer byteBuffer = ByteBuffer.allocate(98);
    byteBuffer.order(ByteOrder.BIG_ENDIAN);

    byteBuffer.putLong(0, this.getConnectionId());
    byteBuffer.putInt(8, this.getAction().value());
    byteBuffer.putInt(12, this.getTransactionId());
    byteBuffer.position(16);
    byteBuffer.put(infoHash.getBytes());
    byteBuffer.position(36);
    byteBuffer.put(peerId.getBytes());
    byteBuffer.putLong(56, downloaded);
    byteBuffer.putLong(64, left);
    byteBuffer.putLong(72, uploaded);
    byteBuffer.putInt(80, this.getEvent().value());
    byteBuffer.putInt(84, peerInfo.getIpAddress());
    byteBuffer.putInt(88, key);
    byteBuffer.putInt(92, numWant);
    byteBuffer.putChar(96, (char) peerInfo.getPort());

    byteBuffer.flip();

    return byteBuffer.array();
  }