Пример #1
1
 public static void checkTCPConnections() {
   for (int i = 0; i < playerConnections.size(); i++) {
     // Create ByteBuffer
     ByteBuffer b = ByteBuffer.allocate(65536);
     b.clear();
     // Read from Player Connection, if error, remove connection
     try {
       int bytesRead = playerConnections.get(i).read(b);
       if (bytesRead == 0) continue;
       if (bytesRead == -1) {
         // Removes player from connections if disconnected.
         playerConnections.remove(i);
         --i;
         continue;
       }
       if (b.array().length > 0) {
         // Trims info to the bytes which are actually read.
         byte[] info = new byte[bytesRead];
         for (int x = 0; x < bytesRead; x++) {
           info[x] = b.array()[x];
         }
         playerConnections.get(i).addData(info);
       }
     } catch (IOException e) {
       playerConnections.remove(i);
       --i;
       continue;
     }
   }
 }
Пример #2
0
  @Override
  public TransformationResult getMoreData(byte opCode, boolean fin, int rsv, ByteBuffer dest)
      throws IOException {
    // Control frames are never compressed and may appear in the middle of
    // a WebSocket method. Pass them straight through.
    if (Util.isControl(opCode)) {
      return next.getMoreData(opCode, fin, rsv, dest);
    }

    if (!Util.isContinuation(opCode)) {
      // First frame in new message
      skipDecompression = (rsv & RSV_BITMASK) == 0;
    }

    // Pass uncompressed frames straight through.
    if (skipDecompression) {
      return next.getMoreData(opCode, fin, rsv, dest);
    }

    int written;
    boolean usedEomBytes = false;

    while (dest.remaining() > 0) {
      // Space available in destination. Try and fill it.
      try {
        written =
            inflater.inflate(dest.array(), dest.arrayOffset() + dest.position(), dest.remaining());
      } catch (DataFormatException e) {
        throw new IOException(sm.getString("perMessageDeflate.deflateFailed"), e);
      }
      dest.position(dest.position() + written);

      if (inflater.needsInput() && !usedEomBytes) {
        if (dest.hasRemaining()) {
          readBuffer.clear();
          TransformationResult nextResult =
              next.getMoreData(opCode, fin, (rsv ^ RSV_BITMASK), readBuffer);
          inflater.setInput(readBuffer.array(), readBuffer.arrayOffset(), readBuffer.position());
          if (TransformationResult.UNDERFLOW.equals(nextResult)) {
            return nextResult;
          } else if (TransformationResult.END_OF_FRAME.equals(nextResult)
              && readBuffer.position() == 0) {
            if (fin) {
              inflater.setInput(EOM_BYTES);
              usedEomBytes = true;
            } else {
              return TransformationResult.END_OF_FRAME;
            }
          }
        }
      } else if (written == 0) {
        if (fin && (isServer && !clientContextTakeover || !isServer && !serverContextTakeover)) {
          inflater.reset();
        }
        return TransformationResult.END_OF_FRAME;
      }
    }

    return TransformationResult.OVERFLOW;
  }
Пример #3
0
 @Test
 public void testReadAndWriteCaptureChannels() throws IOException {
   String blobName = "test-read-and-write-capture-channels-blob";
   BlobInfo blob = BlobInfo.builder(BUCKET, blobName).build();
   byte[] stringBytes;
   BlobWriteChannel writer = storage.writer(blob);
   stringBytes = BLOB_STRING_CONTENT.getBytes(UTF_8);
   writer.write(ByteBuffer.wrap(BLOB_BYTE_CONTENT));
   RestorableState<BlobWriteChannel> writerState = writer.capture();
   BlobWriteChannel secondWriter = writerState.restore();
   secondWriter.write(ByteBuffer.wrap(stringBytes));
   secondWriter.close();
   ByteBuffer readBytes;
   ByteBuffer readStringBytes;
   BlobReadChannel reader = storage.reader(blob.blobId());
   reader.chunkSize(BLOB_BYTE_CONTENT.length);
   readBytes = ByteBuffer.allocate(BLOB_BYTE_CONTENT.length);
   reader.read(readBytes);
   RestorableState<BlobReadChannel> readerState = reader.capture();
   BlobReadChannel secondReader = readerState.restore();
   readStringBytes = ByteBuffer.allocate(stringBytes.length);
   secondReader.read(readStringBytes);
   reader.close();
   secondReader.close();
   assertArrayEquals(BLOB_BYTE_CONTENT, readBytes.array());
   assertEquals(BLOB_STRING_CONTENT, new String(readStringBytes.array(), UTF_8));
   assertTrue(storage.delete(BUCKET, blobName));
 }
Пример #4
0
  public SpillRecord(Path indexFileName, JobConf job, Checksum crc, String expectedIndexOwner)
      throws IOException {

    final FileSystem rfs = FileSystem.getLocal(job).getRaw();
    final DataInputStream in =
        new DataInputStream(
            SecureIOUtils.openForRead(
                new File(indexFileName.toUri().getPath()), expectedIndexOwner, null));
    try {
      final long length = rfs.getFileStatus(indexFileName).getLen();
      final int partitions = (int) length / MAP_OUTPUT_INDEX_RECORD_LENGTH;
      final int size = partitions * MAP_OUTPUT_INDEX_RECORD_LENGTH;

      buf = ByteBuffer.allocate(size);
      if (crc != null) {
        crc.reset();
        CheckedInputStream chk = new CheckedInputStream(in, crc);
        IOUtils.readFully(chk, buf.array(), 0, size);
        if (chk.getChecksum().getValue() != in.readLong()) {
          throw new ChecksumException("Checksum error reading spill index: " + indexFileName, -1);
        }
      } else {
        IOUtils.readFully(in, buf.array(), 0, size);
      }
      entries = buf.asLongBuffer();
    } finally {
      in.close();
    }
  }
Пример #5
0
  /**
   * Get the frequency value for a word form. It is taken from the first entry with this word form.
   *
   * @param word the word to be tested
   * @return frequency value in range: 0..FREQ_RANGE-1 (0: less frequent).
   */
  public int getFrequency(final CharSequence word) {
    if (!dictionaryMetadata.isFrequencyIncluded()) {
      return 0;
    }

    final byte separator = dictionaryMetadata.getSeparator();
    try {
      byteBuffer = charSequenceToBytes(word);
    } catch (UnmappableInputException e) {
      return 0;
    }

    final MatchResult match =
        matcher.match(matchResult, byteBuffer.array(), 0, byteBuffer.remaining(), rootNode);
    if (match.kind == SEQUENCE_IS_A_PREFIX) {
      final int arc = fsa.getArc(match.node, separator);
      if (arc != 0 && !fsa.isArcFinal(arc)) {
        finalStatesIterator.restartFrom(fsa.getEndNode(arc));
        if (finalStatesIterator.hasNext()) {
          final ByteBuffer bb = finalStatesIterator.next();
          final byte[] ba = bb.array();
          final int bbSize = bb.remaining();
          // the last byte contains the frequency after a separator
          return ba[bbSize - 1] - FIRST_RANGE_CODE;
        }
      }
    }
    return 0;
  }
  public byte[] generateTestPacket() {
    ByteBuffer payload = ByteBuffer.allocate(6 + MAVLINK_MSG_LENGTH + 2);
    payload.put((byte) MAVLinkPacket.MAVLINK_STX); // stx
    payload.put((byte) MAVLINK_MSG_LENGTH); // len
    payload.put((byte) 0); // seq
    payload.put((byte) 255); // sysid
    payload.put((byte) 190); // comp id
    payload.put((byte) MAVLINK_MSG_ID_POSITION_TARGET_LOCAL_NED); // msg id
    payload.putInt(963497464); // time_boot_ms
    payload.putFloat((float) 45.0); // x
    payload.putFloat((float) 73.0); // y
    payload.putFloat((float) 101.0); // z
    payload.putFloat((float) 129.0); // vx
    payload.putFloat((float) 157.0); // vy
    payload.putFloat((float) 185.0); // vz
    payload.putFloat((float) 213.0); // afx
    payload.putFloat((float) 241.0); // afy
    payload.putFloat((float) 269.0); // afz
    payload.putFloat((float) 297.0); // yaw
    payload.putFloat((float) 325.0); // yaw_rate
    payload.putShort((short) 19731); // type_mask
    payload.put((byte) 27); // coordinate_frame

    CRC crc = generateCRC(payload.array());
    payload.put((byte) crc.getLSB());
    payload.put((byte) crc.getMSB());
    return payload.array();
  }
Пример #7
0
  private void calculate() throws UnknownHostException {

    ByteBuffer maskBuffer;
    int targetSize;
    if (inetAddress.getAddress().length == 4) {
      maskBuffer = ByteBuffer.allocate(4).putInt(-1);
      targetSize = 4;
    } else {
      maskBuffer = ByteBuffer.allocate(16).putLong(-1L).putLong(-1L);
      targetSize = 16;
    }

    BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);

    ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    BigInteger ipVal = new BigInteger(1, buffer.array());

    BigInteger startIp = ipVal.and(mask);
    BigInteger endIp = startIp.add(mask.not());

    byte[] startIpArr = toBytes(startIp.toByteArray(), targetSize);
    byte[] endIpArr = toBytes(endIp.toByteArray(), targetSize);

    this.startAddress = InetAddress.getByAddress(startIpArr);
    this.endAddress = InetAddress.getByAddress(endIpArr);
  }
Пример #8
0
 @Override
 public ByteBuffer compress(ByteBuffer in) throws IOException {
   ByteBuffer out = ByteBuffer.allocate(Snappy.maxCompressedLength(in.remaining()));
   int size = Snappy.compress(in.array(), in.position(), in.remaining(), out.array(), 0);
   out.limit(size);
   return out;
 }
Пример #9
0
  /**
   * Decodes a dictionary from the bencoded byte array.
   *
   * @param bencoded_bytes the bencoded form of the dictionary.
   * @param offset the offset into {@code bencoded_bytes} where the dictionary begins.
   * @return an <code>Object[]</code> containing an <code>Integer</code> offset and the decoded
   *     dictionary (as a {@code Map}, in positions 0 and 1, respectively
   * @throws BencodingException if the bencoded object is incorrectly encoded.
   */
  @SuppressWarnings("unchecked")
  private static final Object[] decodeDictionary(byte[] bencoded_bytes, int offset)
      throws BencodingException {
    HashMap map = new HashMap();
    ++offset;
    ByteBuffer info_hash_bytes = null;
    while (bencoded_bytes[offset] != (byte) 'e') {

      // Decode the key, which must be a byte string
      Object[] vals = decodeString(bencoded_bytes, offset);
      ByteBuffer key = (ByteBuffer) vals[1];
      offset = ((Integer) vals[0]).intValue();
      boolean match = true;
      for (int i = 0; i < key.array().length && i < 4; i++) {
        if (!key.equals(ByteBuffer.wrap(new byte[] {'i', 'n', 'f', 'o'}))) {
          match = false;
          break;
        }
      }
      int info_offset = -1;
      if (match) info_offset = offset;
      vals = decode(bencoded_bytes, offset);
      offset = ((Integer) vals[0]).intValue();
      if (match) {
        info_hash_bytes = ByteBuffer.wrap(new byte[offset - info_offset]);
        info_hash_bytes.put(bencoded_bytes, info_offset, info_hash_bytes.array().length);
      } else if (vals[1] instanceof HashMap) {
        info_hash_bytes = (ByteBuffer) vals[2];
      }
      if (vals[1] != null) map.put(key, vals[1]);
    }

    return new Object[] {new Integer(++offset), map, info_hash_bytes};
  }
  public void messageReceived(Identifier i, ByteBuffer m, Map<String, Object> options)
      throws IOException {
    if (logger.level <= Logger.FINE) logger.log("messageReceived(" + i + "," + m + ")");

    if (m.remaining() < HEADER.length) {
      errorHandler.receivedUnexpectedData(i, m.array(), 0, null);
      return;
    }
    byte[] hdr = new byte[HEADER.length];

    m.get(hdr);

    int remaining = m.remaining();
    if (Arrays.equals(HEADER, hdr)) {
      notifyListenersRead(HEADER.length, i, options, false, false); // non-pasthrough part
      notifyListenersRead(remaining, i, options, true, false); // passthrough part
      callback.messageReceived(i, m, options);
      return;
    }

    notifyListenersRead(HEADER.length, i, options, false, false); // non-pasthrough part
    notifyListenersRead(remaining, i, options, true, false); // passthrough part

    errorHandler.receivedUnexpectedData(i, m.array(), 0, null);
  }
Пример #11
0
 /** Called from the ExecutionEngine to request serialized dependencies. */
 public byte[] nextDependencyAsBytes(final int dependencyId) {
   final VoltTable vt = m_dependencyTracker.nextDependency(dependencyId);
   if (vt != null) {
     ByteBuffer buffer = vt.getDirectDataReference();
     if (d)
       LOG.debug(
           String.format(
               "Passing Dependency %d to EE [rows=%d, cols=%d, bytes=%d/%d]\n%s",
               dependencyId,
               vt.getRowCount(),
               vt.getColumnCount(),
               vt.getUnderlyingBufferSize(),
               buffer.array().length,
               vt.toString()));
     assert (buffer.hasArray());
     return (buffer.array());
   }
   // Note that we will hit this after retrieving all the VoltTables for the given dependencyId
   // It does not mean that there were no VoltTables at all, it just means that
   // we have gotten all of them
   else if (d) {
     LOG.warn(
         String.format(
             "Failed to find Dependency %d for EE [dep=%s, count=%d, ids=%s]",
             dependencyId,
             m_dependencyTracker.m_depsById.get(dependencyId),
             m_dependencyTracker.m_depsById.size(),
             m_dependencyTracker.m_depsById.keySet()));
   }
   return null;
 }
Пример #12
0
  /**
   * Returns the SHA1 has associated with the file.
   *
   * @param file
   * @param length
   * @return
   * @throws IOException
   * @throws DatabaseException
   */
  static MessageDigest getSHA1Digest(File file, long length) throws IOException, DatabaseException {

    MessageDigest messageDigest = null;

    try {
      messageDigest = MessageDigest.getInstance("SHA1");
    } catch (NoSuchAlgorithmException e) {
      throw EnvironmentFailureException.unexpectedException(e);
    }
    final FileInputStream fileStream = new FileInputStream(file);
    try {
      ByteBuffer buffer = ByteBuffer.allocate(TRANSFER_BYTES);
      for (long bytes = length; bytes > 0; ) {
        int readSize = (int) Math.min(TRANSFER_BYTES, bytes);
        int readBytes = fileStream.read(buffer.array(), 0, readSize);
        if (readBytes == -1) {
          throw new IOException("Premature EOF. Was expecting: " + readSize);
        }
        messageDigest.update(buffer.array(), 0, readBytes);
        bytes -= readBytes;
      }
    } finally {
      fileStream.close();
    }
    return messageDigest;
  }
Пример #13
0
  private void renderOneCameraAndAddToList(
      final GVRPerspectiveCamera centerCamera, byte[][] byteArrays, int index) {

    renderCamera(mActivity.getAppPtr(), mMainScene, centerCamera, mRenderBundle);
    readRenderResult();
    byteArrays[index] = Arrays.copyOf(mReadbackBuffer.array(), mReadbackBuffer.array().length);
  }
Пример #14
0
  public static WavInfo readHeader(InputStream wavStream) throws IOException, DecoderException {

    ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    wavStream.read(buffer.array(), buffer.arrayOffset(), buffer.capacity());

    buffer.rewind();
    buffer.position(buffer.position() + 20);
    int format = buffer.getShort();
    checkFormat(format == 1, "Unsupported encoding: " + format); // 1 means Linear PCM
    int channels = buffer.getShort();
    checkFormat(channels == 1 || channels == 2, "Unsupported channels: " + channels);
    int rate = buffer.getInt();
    checkFormat(rate <= 48000 && rate >= 11025, "Unsupported rate: " + rate);
    buffer.position(buffer.position() + 6);
    int bits = buffer.getShort();
    checkFormat(bits == 16, "Unsupported bits: " + bits);
    int dataSize = 0;
    while (buffer.getInt() != 0x61746164) { // "data" marker
      Log.d(TAG, "Skipping non-data chunk");
      int size = buffer.getInt();
      wavStream.skip(size);

      buffer.rewind();
      wavStream.read(buffer.array(), buffer.arrayOffset(), 8);
      buffer.rewind();
    }
    dataSize = buffer.getInt();
    checkFormat(dataSize > 0, "wrong datasize: " + dataSize);

    return new WavInfo(rate, channels == 2, dataSize);
  }
 public void receiveSelectResult(P2PSocket<Identifier> socket, boolean canRead, boolean canWrite)
     throws IOException {
   // TODO: Optimization: Check array at each step, to fail faster
   // TODO: Make timeout/cancellable
   if (canWrite) throw new IOException("Never asked to write!");
   if (!canRead) throw new IOException("Can't read!");
   long bytesRead;
   if ((bytesRead = socket.read(buf)) < 0) {
     socket.close();
     return;
   }
   notifyListenersRead(
       (int) bytesRead, socket.getIdentifier(), socket.getOptions(), false, true);
   if (buf.hasRemaining()) {
     socket.register(true, false, this);
   } else {
     if (Arrays.equals(HEADER, buf.array())) {
       // header matched
       cancel();
       callback.incomingSocket(socket);
     } else {
       cancel();
       errorHandler.receivedUnexpectedData(socket.getIdentifier(), buf.array(), 0, null);
       socket.close();
     }
   }
 }
Пример #16
0
 public ByteBuffer encodePage(ByteBuffer page, int pageNumber, int pageOffset)
     throws IOException {
   ByteBuffer bb = _bufH.getPageBuffer(_channel);
   bb.clear();
   simpleEncode(page.array(), bb.array(), pageNumber, pageOffset, page.limit());
   return bb;
 }
Пример #17
0
  public byte[] generateTestPacket() {
    ByteBuffer payload = ByteBuffer.allocate(6 + MAVLINK_MSG_LENGTH + 2);
    payload.put((byte) MAVLinkPacket.MAVLINK_STX); // stx
    payload.put((byte) MAVLINK_MSG_LENGTH); // len
    payload.put((byte) 0); // seq
    payload.put((byte) 255); // sysid
    payload.put((byte) 190); // comp id
    payload.put((byte) MAVLINK_MSG_ID_PARAM_SET); // msg id
    payload.putFloat((float) 17.0); // param_value
    payload.put((byte) 17); // target_system
    payload.put((byte) 84); // target_component
    // param_id
    payload.put((byte) 'G');
    payload.put((byte) 'H');
    payload.put((byte) 'I');
    payload.put((byte) 'J');
    payload.put((byte) 'K');
    payload.put((byte) 'L');
    payload.put((byte) 'M');
    payload.put((byte) 'N');
    payload.put((byte) 'O');
    payload.put((byte) 'P');
    payload.put((byte) 'Q');
    payload.put((byte) 'R');
    payload.put((byte) 'S');
    payload.put((byte) 'T');
    payload.put((byte) 'U');
    payload.put((byte) 'G');
    payload.put((byte) 199); // param_type

    CRC crc = generateCRC(payload.array());
    payload.put((byte) crc.getLSB());
    payload.put((byte) crc.getMSB());
    return payload.array();
  }
Пример #18
0
 private Cell toOnheapCell(
     ByteBuffer valAndTagsBuffer, int vOffset, int tagsLenSerializationSize) {
   byte[] tagsArray = HConstants.EMPTY_BYTE_ARRAY;
   int tOffset = 0;
   if (this.includeTags) {
     if (this.tagCompressionContext == null) {
       tagsArray = valAndTagsBuffer.array();
       tOffset =
           valAndTagsBuffer.arrayOffset()
               + vOffset
               + this.valueLength
               + tagsLenSerializationSize;
     } else {
       tagsArray = Bytes.copy(tagsBuffer, 0, this.tagsLength);
       tOffset = 0;
     }
   }
   return new OnheapDecodedCell(
       Bytes.copy(keyBuffer, 0, this.keyLength),
       currentKey.getRowLength(),
       currentKey.getFamilyOffset(),
       currentKey.getFamilyLength(),
       currentKey.getQualifierOffset(),
       currentKey.getQualifierLength(),
       currentKey.getTimestamp(),
       currentKey.getTypeByte(),
       valAndTagsBuffer.array(),
       valAndTagsBuffer.arrayOffset() + vOffset,
       this.valueLength,
       memstoreTS,
       tagsArray,
       tOffset,
       this.tagsLength);
 }
Пример #19
0
  private void index(final File file) throws IOException {
    final InputStream in = new FileInputStream(file);

    final OutputStream out =
        new BufferedOutputStream(new FileOutputStream(file.getPath() + ".bgzfi"));

    final LongBuffer lb = byteBuffer.order(ByteOrder.BIG_ENDIAN).asLongBuffer();

    long prevPrint = 0;
    pos = 0;

    for (int i = 0; ; ) {
      if (!skipBlock(in)) break;

      if (++i == granularity) {
        i = 0;
        lb.put(0, pos);
        out.write(byteBuffer.array(), 2, 6);

        if (pos - prevPrint >= PRINT_EVERY) {
          System.out.print("-");
          prevPrint = pos;
        }
      }
    }
    lb.put(0, file.length());
    out.write(byteBuffer.array(), 2, 6);
    out.close();
    in.close();
  }
Пример #20
0
 /**
  * 入力データからパケットを構築して送信する。今回はSocketを複数開いたり、 ということは起こらないので本メソッドに集約してしまってる。空文字列が送られてきたら
  * 特殊パターンとしてrefresh用のパケットを構築する(つまり\0単独は特殊パターン)
  *
  * @return 正常終了時は0。サーバへの接続が失われていれば-4。その他I/Oエラー時は-1。
  */
 private int sendPacket(String src) {
   OutputStream writer;
   Log.d("moku99", "sending a packet");
   try {
     if (clientSock.isConnected() == false) {
       return -4;
     }
     writer = clientSock.getOutputStream();
     if (src.equals("")) {
       // 空の特殊パターン
       ByteBuffer buf = ByteBuffer.allocate(8);
       buf.putInt(myId.intValue());
       buf.putInt(0);
       writer.write(buf.array());
     } else {
       // 通常メッセージ送信パターン
       byte[] strBuf = src.getBytes();
       ByteBuffer buf = ByteBuffer.allocate(8 + strBuf.length);
       buf.putInt(myId.intValue());
       buf.putInt(strBuf.length);
       buf.put(strBuf);
       writer.write(buf.array());
     }
   } catch (IOException e) {
     Log.d("moku99", e.getLocalizedMessage());
     return -1;
   }
   return 0;
 }
Пример #21
0
 public static List<ByteBuffer> mergeAdjacentBuffers(List<ByteBuffer> samples) {
   ArrayList<ByteBuffer> nuSamples = new ArrayList<ByteBuffer>(samples.size());
   for (ByteBuffer buffer : samples) {
     int lastIndex = nuSamples.size() - 1;
     if (lastIndex >= 0
         && buffer.hasArray()
         && nuSamples.get(lastIndex).hasArray()
         && buffer.array() == nuSamples.get(lastIndex).array()
         && nuSamples.get(lastIndex).arrayOffset() + nuSamples.get(lastIndex).limit()
             == buffer.arrayOffset()) {
       ByteBuffer oldBuffer = nuSamples.remove(lastIndex);
       ByteBuffer nu =
           ByteBuffer.wrap(
                   buffer.array(), oldBuffer.arrayOffset(), oldBuffer.limit() + buffer.limit())
               .slice();
       // We need to slice here since wrap([], offset, length) just sets position and not the
       // arrayOffset.
       nuSamples.add(nu);
     } else if (lastIndex >= 0
         && buffer instanceof MappedByteBuffer
         && nuSamples.get(lastIndex) instanceof MappedByteBuffer
         && nuSamples.get(lastIndex).limit()
             == nuSamples.get(lastIndex).capacity() - buffer.capacity()) {
       // This can go wrong - but will it?
       ByteBuffer oldBuffer = nuSamples.get(lastIndex);
       oldBuffer.limit(buffer.limit() + oldBuffer.limit());
     } else {
       nuSamples.add(buffer);
     }
   }
   return nuSamples;
 }
Пример #22
0
  @Override
  public List<Framedata> translateFrame(ByteBuffer buffer)
      throws LimitExedeedException, InvalidDataException {
    List<Framedata> frames = new LinkedList<Framedata>();
    Framedata cur;

    if (incompleteframe != null) {
      // complete an incomplete frame
      while (true) {
        try {
          buffer.mark();
          int available_next_byte_count = buffer.remaining(); // The number of bytes received
          int expected_next_byte_count =
              incompleteframe.remaining(); // The number of bytes to complete the incomplete frame

          if (expected_next_byte_count > available_next_byte_count) {
            // did not receive enough bytes to complete the frame
            incompleteframe.put(buffer.array(), buffer.position(), available_next_byte_count);
            buffer.position(buffer.position() + available_next_byte_count);
            return Collections.emptyList();
          }
          incompleteframe.put(buffer.array(), buffer.position(), expected_next_byte_count);
          buffer.position(buffer.position() + expected_next_byte_count);

          cur = translateSingleFrame((ByteBuffer) incompleteframe.duplicate().position(0));
          frames.add(cur);
          incompleteframe = null;
          break; // go on with the normal frame receival
        } catch (IncompleteException e) {
          // extending as much as suggested
          @SuppressWarnings("unused")
          int oldsize = incompleteframe.limit();
          ByteBuffer extendedframe = ByteBuffer.allocate(checkAlloc(e.getPreferedSize()));
          assert (extendedframe.limit() > incompleteframe.limit());
          incompleteframe.rewind();
          extendedframe.put(incompleteframe);
          incompleteframe = extendedframe;

          return translateFrame(buffer);
        }
      }
    }

    while (buffer.hasRemaining()) { // Read as much as possible full frames
      buffer.mark();
      try {
        cur = translateSingleFrame(buffer);
        frames.add(cur);
      } catch (IncompleteException e) {
        // remember the incomplete data
        buffer.reset();
        int pref = e.getPreferedSize();
        incompleteframe = ByteBuffer.allocate(checkAlloc(pref));
        incompleteframe.put(buffer);
        break;
      }
    }
    return frames;
  }
Пример #23
0
 @Override
 public Writable create(Object value, TypeConverter typeConverter, Holder<Integer> size) {
   BytesWritable writable = new BytesWritable();
   ByteBuffer bb = (ByteBuffer) value;
   writable.set(bb.array(), 0, bb.array().length);
   size.value = bb.array().length;
   return writable;
 }
Пример #24
0
 public static byte[] toBytes(char[] chars) {
   CharBuffer charBuffer = CharBuffer.wrap(chars);
   ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
   byte[] bytes =
       Arrays.copyOfRange(byteBuffer.array(), byteBuffer.position(), byteBuffer.limit());
   Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
   Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
   return bytes;
 }
 @Test
 public void testRemoveNotificationsByKeyHash() throws Exception {
   ByteBuffer epKeyHash = ByteBuffer.wrap(generateBytes());
   generateEndpointNotification(epKeyHash, 3);
   unicastNotificationDao.removeNotificationsByKeyHash(epKeyHash.array());
   List<CassandraEndpointNotification> found =
       unicastNotificationDao.findNotificationsByKeyHash(epKeyHash.array());
   Assert.assertTrue(found.isEmpty());
 }
  private void send(int mode) {

    try {
      DatagramSocket socket;
      socket = new DatagramSocket(app.recipientPort);

      int universe = app.universeSlider.getValue();
      int channel1 = app.channelSlider.getValue();
      int val1 = app.val1Slider.getValue();
      int val2 = app.val2Slider.getValue();
      int val3 = app.val3Slider.getValue();

      ArtNetDMXData dmx = new ArtNetDMXData();
      dmx.setUniverse((byte) universe);

      // we don't use these parts of the spec.
      dmx.setPhysical((byte) 1);
      dmx.Sequence = (byte) 0;

      // set light data
      byte[] data = new byte[512];
      for (int i = 0; i < 512; i++) {
        switch (mode) {
          case (ALL_FF_MODE):
            data[i] = (byte) 255;
            break;
          case (ALL_00_MODE):
            data[i] = (byte) 0;
            break;
          default:
            if (i == channel1 - 1) {
              data[i] = (byte) val1;
            } else if (i == channel1) {
              data[i] = (byte) val2;
            } else if (i == channel1 + 1) {
              data[i] = (byte) val3;
            } else {
              data[i] = (byte) 0;
            }
            break;
        }
      }
      dmx.setData(data);

      ByteBuffer b = dmx.getBytes();

      System.out.println(Util.bytesToHex(b.array()));

      DatagramPacket packet =
          new DatagramPacket(b.array(), b.position(), app.recipient, app.recipientPort);

      socket.send(packet);
      socket.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #27
0
    public ByteBuffer encodePage(ByteBuffer page, int pageNumber, int pageOffset)
        throws IOException {
      assertEquals(0, pageOffset);
      assertEquals(_channel.getFormat().PAGE_SIZE, page.limit());

      ByteBuffer bb = _bufH.getPageBuffer(_channel);
      bb.clear();
      fullEncode(page.array(), bb.array(), pageNumber);
      return bb;
    }
Пример #28
0
  public LineManager(String filename) throws IOException {
    mNumLines = 0;

    BufferedReader content = new BufferedReader(new FileReader(filename), BLOCK_SIZE);

    // For Directory
    BufferedOutputStream directory = new BufferedOutputStream(new FileOutputStream(DIRECTORY_PATH));
    int pageNo = 0; // 0-based index to make computation easier
    int slotNo = 1;

    // For Data
    ByteBuffer dataBuffer = ByteBuffer.allocate(BLOCK_SIZE);
    BufferedOutputStream data = new BufferedOutputStream(new FileOutputStream(DATA_PATH));
    int initialIndex = BLOCK_SIZE - 3 * INT_SIZE; // Each slot index is
    // offset, length pair
    // Each page ends with
    // # slots on page
    int indexPos = initialIndex;
    String curLine;
    // KNOWN BUG: lineLen > BLOCK_SIZE
    while ((curLine = content.readLine()) != null) {
      int lineLen = curLine.length();
      byte[] lineBytes = curLine.getBytes("US-ASCII");
      if (dataBuffer.position() + lineLen > indexPos) { // End of page
        dataBuffer.putInt(BLOCK_SIZE - INT_SIZE, slotNo - 1);
        // Write number of slots on page
        data.write(dataBuffer.array());

        // Reset info
        dataBuffer.clear();
        indexPos = initialIndex;
        pageNo++;
        slotNo = 1;
      }
      dataBuffer.putInt(indexPos, dataBuffer.position());
      dataBuffer.putInt(indexPos + INT_SIZE, lineLen);
      dataBuffer.put(lineBytes);
      indexPos -= 2 * INT_SIZE;

      directory.write(LineManager.intToBytes(pageNo));
      directory.write(LineManager.intToBytes(slotNo));

      slotNo++;
      mNumLines++;
    }
    data.write(dataBuffer.array());
    data.flush();
    directory.flush();
    content.close();
    data.close();
    directory.close();

    mDirectoryFile = new RandomAccessFile(DIRECTORY_PATH, "r");
    mDataFile = new RandomAccessFile(DATA_PATH, "r");
  }
 @Override
 public void processMessage(ByteBuffer message) throws Exception {
   if (!fileCreated) {
     createFile();
     fileCreated = true;
   }
   reusableLengthBuffer.flip();
   reusableLengthBuffer.putInt(message.array().length);
   bos.write(reusableLengthBuffer.array());
   bos.write(message.array());
 }
Пример #30
0
  public void onReceive(ByteBuffer b) {
    if (b.remaining() == 4) {
      Common.logError("invalid packet:");
      byte[] data = new byte[b.remaining()];
      b.get(data);
      Common.print_dump(data);
      //	retry( TLMessage.keyAt(  TLMessage.size() - 1) );
      return;
    }

    try {
      if (b.getLong() == 0) { // auth_key_id
        b.getLong(); // message_id
        b.getInt(); // message length
        process(TL.deserialize(b));
      } else {
        byte[] msg_key = new byte[16];
        b.get(msg_key);
        byte[] data = new byte[b.remaining()];
        b.get(data);

        synchronized (aes) {
          aes.prepare(false, msg_key, auth_key);
          data = aes.IGE(data, false);
        }

        ByteBuffer btmp = ByteBuffer.wrap(data);
        btmp.order(ByteOrder.LITTLE_ENDIAN);
        server_salt = btmp.getLong();
        btmp.getLong(); // session_id
        cur_message_id = btmp.getLong(); // message_id
        cur_msg_seq = btmp.getInt(); // seq_no
        // if (cur_msg_seq > seqno)
        //	seqno = cur_msg_seq + cur_msg_seq % 2;
        int bsize = btmp.getInt();
        if (bsize < 0 || bsize > 1024 * 1024) {
          Common.print_dump(btmp.array());
          Common.logError(new String(btmp.array()));
          Common.logError("FFFUUUUUUUUUUU!!!");
        }

        b = BufferAlloc(bsize);
        btmp.get(b.array());
        b.getInt();
        ack_message(cur_msg_seq, cur_message_id);
        b.position(0);

        process(TL.deserialize(b));
        send_accept();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }