コード例 #1
1
ファイル: FilePersister.java プロジェクト: nothize/suite
  public B_Tree.Page<Key> load(int pageNo) {
    try {
      ByteBuffer buffer = ByteBuffer.allocate(pageSize);
      channel.read(buffer, pageNo * pageSize);
      buffer.rewind();

      B_Tree.Page<Key> page = new B_Tree.Page<Key>(pageNo);
      List<B_Tree.KeyPointer<Key>> keyPointers = page.keyPointers;

      char nodeType = buffer.getChar();
      int size = buffer.getInt();

      for (int i = 0; i < size; i++) {
        Key key = keyAccessor.read(buffer);

        if (nodeType == INTERNAL) {
          int branch = buffer.getInt();
          addBranch(keyPointers, key, branch);
        } else if (nodeType == LEAF) {
          Value value = valueAccessor.read(buffer);
          addLeaf(keyPointers, key, value);
        }
      }

      return page;
    } catch (IOException ex) {
      throw new RuntimeException(ex);
    }
  }
コード例 #2
0
  public void testWriteAndRead() {
    String group = "Testgroup";
    state.write(group, attach);
    ByteBuffer buffer = attach.getWriteBuffer2();
    int length;
    byte[] packet;

    buffer.flip();
    length = buffer.getInt();
    buffer.getInt(); // operation
    length -= 4;
    packet = new byte[length];

    for (int i = 0; i < length; i++) {
      packet[i] = buffer.get();
    }
    buffer.compact();

    try {
      InputStream bais = new ByteArrayInputStream(packet);
      ObjectInputStream ois;
      ois = new ObjectInputStream(bais);
      state.read(ois);

      assertEquals(true, group.equals(state.getGroup()));

    } catch (Exception e) {
      fail();
    }
  }
コード例 #3
0
ファイル: MurmurHash.java プロジェクト: AlfieC/HCTeams-1
 public static int hash(final ByteBuffer buf, final int seed) {
   final ByteOrder byteOrder = buf.order();
   buf.order(ByteOrder.LITTLE_ENDIAN);
   final int m = 1540483477;
   final int r = 24;
   int h = seed ^ buf.remaining();
   while (buf.remaining() >= 4) {
     int k = buf.getInt();
     k *= m;
     k ^= k >>> r;
     k *= m;
     h *= m;
     h ^= k;
   }
   if (buf.remaining() > 0) {
     final ByteBuffer finish = ByteBuffer.allocate(4).order(ByteOrder.LITTLE_ENDIAN);
     finish.put(buf).rewind();
     h ^= finish.getInt();
     h *= m;
   }
   h ^= h >>> 13;
   h *= m;
   h ^= h >>> 15;
   buf.order(byteOrder);
   return h;
 }
コード例 #4
0
ファイル: MAVLinkMessage.java プロジェクト: yueyehu/cjMAVSim
 private Object getValue(MAVLinkDataType type, int offset) {
   switch (type) {
     case CHAR:
       return payloadBB.get(offset);
     case UINT8:
       return payloadBB.get(offset) & 0xFF;
     case INT8:
       return (int) payloadBB.get(offset);
     case UINT16:
       return payloadBB.getShort(offset) & 0xFFFF;
     case INT16:
       return (int) payloadBB.getShort(offset);
     case UINT32:
       return payloadBB.getInt(offset) & 0xFFFFFFFFl;
     case INT32:
       return payloadBB.getInt(offset);
     case UINT64:
       return payloadBB.getLong(offset);
     case INT64:
       return payloadBB.getLong(offset);
     case FLOAT:
       return payloadBB.getFloat(offset);
     case DOUBLE:
       return payloadBB.getDouble(offset);
     default:
       throw new RuntimeException("Unknown type: " + type);
   }
 }
コード例 #5
0
  public static CompressedLongsIndexedSupplier fromByteBuffer(ByteBuffer buffer, ByteOrder order) {
    byte versionFromBuffer = buffer.get();

    if (versionFromBuffer == version) {
      final int totalSize = buffer.getInt();
      final int sizePer = buffer.getInt();
      final CompressedObjectStrategy.CompressionStrategy compression =
          CompressedObjectStrategy.CompressionStrategy.forId(buffer.get());
      return new CompressedLongsIndexedSupplier(
          totalSize,
          sizePer,
          GenericIndexed.read(
              buffer,
              CompressedLongBufferObjectStrategy.getBufferForOrder(order, compression, sizePer)),
          compression);
    } else if (versionFromBuffer == LZF_VERSION) {
      final int totalSize = buffer.getInt();
      final int sizePer = buffer.getInt();
      final CompressedObjectStrategy.CompressionStrategy compression =
          CompressedObjectStrategy.CompressionStrategy.LZF;
      return new CompressedLongsIndexedSupplier(
          totalSize,
          sizePer,
          GenericIndexed.read(
              buffer,
              CompressedLongBufferObjectStrategy.getBufferForOrder(order, compression, sizePer)),
          compression);
    }

    throw new IAE("Unknown version[%s]", versionFromBuffer);
  }
コード例 #6
0
  @NonNull
  protected static Map<String, Chunk> readChunks(@NonNull File file) throws IOException {
    Map<String, Chunk> chunks = Maps.newHashMap();

    byte[] fileBuffer = Files.toByteArray(file);
    ByteBuffer buffer = ByteBuffer.wrap(fileBuffer);

    byte[] sig = new byte[8];
    buffer.get(sig);

    assertTrue(Arrays.equals(sig, SIGNATURE));

    byte[] data, type;
    int len;
    int crc32;

    while (buffer.hasRemaining()) {
      len = buffer.getInt();

      type = new byte[4];
      buffer.get(type);

      data = new byte[len];
      buffer.get(data);

      // crc
      crc32 = buffer.getInt();

      Chunk chunk = new Chunk(type, data, crc32);
      chunks.put(chunk.getTypeAsString(), chunk);
    }

    return chunks;
  }
コード例 #7
0
ファイル: ProtoBackend.java プロジェクト: newsky/sparrow
 public TaskRunnable(
     String requestId, TFullTaskId taskId, ByteBuffer message, TResourceVector taskResources) {
   this.benchmarkId = message.getInt();
   this.benchmarkIterations = message.getInt();
   this.taskResources = taskResources;
   this.taskId = taskId;
 }
コード例 #8
0
ファイル: AliasBox.java プロジェクト: 2php/jcodec
  public void parse(ByteBuffer is) {
    super.parse(is);
    if ((flags & 0x1) != 0) // self ref
    return;
    type = NIOUtils.readString(is, 4);
    recordSize = is.getShort();
    version = is.getShort();
    kind = is.getShort();
    volumeName = NIOUtils.readPascalStringL(is, 27);
    volumeCreateDate = is.getInt();
    volumeSignature = is.getShort();
    volumeType = is.getShort();
    parentDirId = is.getInt();
    fileName = NIOUtils.readPascalStringL(is, 63);
    fileNumber = is.getInt();
    createdLocalDate = is.getInt();
    fileTypeName = NIOUtils.readString(is, 4);
    creatorName = NIOUtils.readString(is, 4);
    nlvlFrom = is.getShort();
    nlvlTo = is.getShort();
    volumeAttributes = is.getInt();
    fsId = is.getShort();
    NIOUtils.skip(is, 10);

    extra = new ArrayList<ExtraField>();
    while (true) {
      short type = is.getShort();
      if (type == -1) break;
      int len = is.getShort();
      byte[] bs = NIOUtils.toArray(NIOUtils.read(is, (len + 1) & 0xfffffffe));
      if (bs == null) break;
      extra.add(new ExtraField(type, len, bs));
    }
  }
コード例 #9
0
  public DataFileAccessorImpl(final File file) throws Exception {
    this.fileInfo = file;
    this.file = new RandomAccessFile(file, "rw");

    try {
      this.channel = this.file.getChannel();

      final ByteBuffer buffer = ByteBuffer.allocate(HEADER_SIZE);

      while (buffer.hasRemaining()) {
        final int rc = this.channel.read(buffer);
        logger.debug("Read {} bytes", rc);
      }

      buffer.flip();

      final int magic = buffer.getInt();
      final int version = buffer.getInt();
      this.start = new Date(buffer.getLong());
      this.end = new Date(buffer.getLong());

      logger.debug(
          "Header - magic: {}, version: {}, start: {}, end: {}",
          new Object[] {magic, version, this.start, this.end});

      if (logger.isDebugEnabled()) {
        logger.debug("File position after header: {}", this.channel.position());
      }
      // position is at end of file
    } catch (final Exception e) {
      logger.warn("Failed to open file", e);
      this.file.close();
      throw e;
    }
  }
コード例 #10
0
  public void testDecode() throws EncodingException, DecodingException {
    PngStegoImage encodedImage = new PngStegoImage();

    encodedImage.setImageBitmap(mCoverImage);
    encodedImage.setEmbeddedData(mData);
    encodedImage.encode();

    byte[] encodedImageBytes = encodedImage.getImageBytes();

    PngStegoImage decodedImage = new PngStegoImage();
    decodedImage.setImageBytes(encodedImageBytes);
    decodedImage.decode();

    byte[] decodedBytes = decodedImage.getEmbeddedData();

    assertNotNull(decodedBytes);

    assertEquals(mData.length, decodedBytes.length);

    ByteBuffer b = ByteBuffer.wrap(decodedBytes).order(Constants.BYTE_ORDER);

    //
    // We should get the same values back as we embedded
    //
    assertEquals(1, b.getInt());
    assertEquals(-12, b.getInt());
    assertEquals(123, b.getInt());
    assertEquals(-1234, b.getInt());
    assertEquals(12345, b.getInt());
    assertEquals(-123456, b.getInt());
  }
コード例 #11
0
  public void deserialize(ByteBuffer bb) {
    stamp = Serialization.readTime(bb);

    int __joint_names_len = bb.getInt();
    joint_names = new java.util.ArrayList<java.lang.String>(__joint_names_len);
    for (int __i = 0; __i < __joint_names_len; __i++) {
      joint_names.add(Serialization.readString(bb));
    }

    int __frame_ids_len = bb.getInt();
    frame_ids = new java.util.ArrayList<java.lang.String>(__frame_ids_len);
    for (int __i = 0; __i < __frame_ids_len; __i++) {
      frame_ids.add(Serialization.readString(bb));
    }

    int __child_frame_ids_len = bb.getInt();
    child_frame_ids = new java.util.ArrayList<java.lang.String>(__child_frame_ids_len);
    for (int __i = 0; __i < __child_frame_ids_len; __i++) {
      child_frame_ids.add(Serialization.readString(bb));
    }

    int __poses_len = bb.getInt();
    poses = new java.util.ArrayList<ros.pkg.geometry_msgs.msg.Pose>(__poses_len);
    for (int __i = 0; __i < __poses_len; __i++) {
      ros.pkg.geometry_msgs.msg.Pose __tmp = new ros.pkg.geometry_msgs.msg.Pose();
      __tmp.deserialize(bb);
      poses.add(__tmp);
      ;
    }
  }
コード例 #12
0
ファイル: LeadingFrame.java プロジェクト: JacobDu/QrPlayer
 /**
  * Creates the leading frame.
  *
  * @param buffer the buffer
  * @return the leading frame
  */
 public static LeadingFrame createLeadingFrame(final ByteBuffer buffer) {
   final LeadingFrame result = new LeadingFrame();
   // magic 4 bytes 0xdeadbeef
   // version 4 bytes int
   // comprType 1 byte
   // sliceCount 4 bytes int
   // sliceDuration 8 bytes long
   // origFileSize 4 bytes int
   // compressedSize 4 bytes int
   // fileNameLen 4 bytes int
   // fileName
   final byte[] magic = new byte[MAGIC_LEN];
   buffer.get(magic);
   if (!Arrays.equals(magic, MAGIC)) {
     throw new IllegalArgumentException("The buffer is not a legal leading frame.");
   }
   result.setVersion(buffer.getInt());
   result.setComprType(CompressType.getById(buffer.get()));
   result.setSliceCount(buffer.getInt());
   result.setSliceDuration(buffer.getLong());
   result.setOrigFileSize(buffer.getInt());
   result.setCompressedSize(buffer.getInt());
   final int fileNameLen = buffer.getInt();
   final byte[] fileNameArray = new byte[fileNameLen];
   buffer.get(fileNameArray);
   result.setOrigFileName(new String(fileNameArray));
   return result;
 }
コード例 #13
0
  private static void parseTCPMsg(byte[] msg) throws UnknownHostException {
    switch (msg[0]) {
      case 0x00:
        if (msg[1] == 0x01) System.out.println("Server: OPEN");
        else System.out.println("Server: CLOSED");
        break;
      case 0x01:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else {
          ByteBuffer buffer = ByteBuffer.wrap(Arrays.copyOfRange(msg, 1, msg.length));
          userId = new UUID(buffer.getLong(), buffer.getLong());
          groupIp =
              InetAddress.getByAddress(ByteBuffer.allocate(4).putInt(buffer.getInt()).array());

          // connect to the group and start receiving
          udpSocket.connect(groupIp.getHostAddress());
          udpSocket.startReceive(new UDPHandler());

          System.out.printf(
              "User ID: %s\nGroup IP: %s\nPort: %d\n",
              userId.toString(), groupIp.getHostAddress(), buffer.getInt());
        }
        break;
      case 0x02:
        if (msg[1] == 0x00)
          System.out.printf("[ERR]: %s", new String(Arrays.copyOfRange(msg, 2, msg.length)));
        else System.out.println("Successfully deregestered");
      default:
        System.out.println("[ERR] Inavlid msg");
    }
  }
コード例 #14
0
ファイル: FieldFormat.java プロジェクト: ecmnet/MAVGCL
 private Object getSingleValue(ByteBuffer buffer) {
   Object v;
   if (type.equals("float")) {
     v = buffer.getFloat();
   } else if (type.equals("double")) {
     v = buffer.getDouble();
   } else if (type.equals("int8_t") || type.equals("bool")) {
     v = (int) buffer.get();
   } else if (type.equals("uint8_t")) {
     v = buffer.get() & 0xFF;
   } else if (type.equals("int16_t")) {
     v = (int) buffer.getShort();
   } else if (type.equals("uint16_t")) {
     v = buffer.getShort() & 0xFFFF;
   } else if (type.equals("int32_t")) {
     v = buffer.getInt();
   } else if (type.equals("uint32_t")) {
     v = buffer.getInt() & 0xFFFFFFFFl;
   } else if (type.equals("int64_t")) {
     v = buffer.getLong();
   } else if (type.equals("uint64_t")) {
     v = buffer.getLong();
   } else if (type.equals("char")) {
     v = buffer.get();
   } else {
     throw new RuntimeException("Unsupported type: " + type);
   }
   return v;
 }
コード例 #15
0
  /** Initialize this structure from a ByteBuffer */
  public void setData(ByteBuffer data) {
    setFormat(data.getInt());
    setItalicAngle(data.getInt());
    setUnderlinePosition(data.getShort());
    setUnderlineThickness(data.getShort());
    setIsFixedPitch(data.getShort());
    data.getShort();
    setMinMemType42(data.getInt());
    setMaxMemType42(data.getInt());
    setMinMemType1(data.getInt());
    setMaxMemType1(data.getInt());

    // create the map, based on the type
    switch (format) {
      case 0x10000:
        nameMap = new PostMapFormat0();
        break;
      case 0x20000:
        nameMap = new PostMapFormat2();
        break;
      case 0x30000:
        // empty post map.
        nameMap = new PostMap();
        break;
      default:
        nameMap = new PostMap();
        System.out.println("Unknown post map type: " + Integer.toHexString(format));
        break;
    }

    // fill in the data in the map
    nameMap.setData(data);
  }
コード例 #16
0
ファイル: WavInfo.java プロジェクト: BloomWave/bloom-app
  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);
  }
コード例 #17
0
ファイル: UPerf.java プロジェクト: xiangxuner/JGroups
    public Object objectFromBuffer(byte[] buffer, int offset, int length) throws Exception {
      ByteBuffer buf = ByteBuffer.wrap(buffer, offset, length);

      byte type = buf.get();
      switch (type) {
        case START:
        case GET_CONFIG:
          return new MethodCall(type);
        case SET_OOB:
        case SET_SYNC:
          return new MethodCall(type, buf.get() == 1);
        case SET_NUM_MSGS:
        case SET_NUM_THREADS:
        case SET_MSG_SIZE:
        case SET_ANYCAST_COUNT:
          return new MethodCall(type, buf.getInt());
        case GET:
          return new MethodCall(type, buf.getLong());
        case PUT:
          Long longarg = buf.getLong();
          int len = buf.getInt();
          byte[] arg2 = new byte[len];
          buf.get(arg2, 0, arg2.length);
          return new MethodCall(type, longarg, arg2);
        case SET_READ_PERCENTAGE:
          return new MethodCall(type, buf.getDouble());
        default:
          throw new IllegalStateException("type " + type + " not known");
      }
    }
コード例 #18
0
  public static CompressedVSizeIntsIndexedSupplier fromByteBuffer(
      ByteBuffer buffer, ByteOrder order) {
    byte versionFromBuffer = buffer.get();

    if (versionFromBuffer == version) {
      final int numBytes = buffer.get();
      final int totalSize = buffer.getInt();
      final int sizePer = buffer.getInt();
      final int chunkBytes = sizePer * numBytes + bufferPadding(numBytes);

      final CompressedObjectStrategy.CompressionStrategy compression =
          CompressedObjectStrategy.CompressionStrategy.forId(buffer.get());

      return new CompressedVSizeIntsIndexedSupplier(
          totalSize,
          sizePer,
          numBytes,
          GenericIndexed.read(
              buffer,
              CompressedByteBufferObjectStrategy.getBufferForOrder(order, compression, chunkBytes)),
          compression);
    }

    throw new IAE("Unknown version[%s]", versionFromBuffer);
  }
コード例 #19
0
ファイル: qfiles.java プロジェクト: bbodi/Kuake2
    public darea_t(ByteBuffer bb) {

      bb.order(ByteOrder.LITTLE_ENDIAN);

      numareaportals = bb.getInt();
      firstareaportal = bb.getInt();
    }
コード例 #20
0
ファイル: Debug.java プロジェクト: ajurcik/oit4cb
 public void writeCaps(GL4 gl, int capsArrayBuffer, int count) throws IOException {
   try (BufferedWriter writer =
       new BufferedWriter(new FileWriter(new File(debugDir, "caps.txt")))) {
     // write counts and planes
     gl.glBindBuffer(GL_SHADER_STORAGE_BUFFER, capsArrayBuffer);
     ByteBuffer capsArray = gl.glMapBuffer(GL_SHADER_STORAGE_BUFFER, GL_READ_ONLY);
     for (int i = 0; i < count; i++) {
       Vector4f position = getVec4(capsArray, i * Scene.SIZEOF_CAP);
       Vector4f plane = getVec4(capsArray, i * Scene.SIZEOF_CAP + 16);
       int atomIdx = capsArray.getInt(i * Scene.SIZEOF_CAP + 32);
       int label = capsArray.getInt(i * Scene.SIZEOF_CAP + 36);
       int padding0 = capsArray.getInt(i * Scene.SIZEOF_CAP + 40);
       int padding1 = capsArray.getInt(i * Scene.SIZEOF_CAP + 44);
       writer.append(String.format("%4d: ", i));
       writer.append(
           String.format(
               "position: [%f %f %f %f], ", position.x, position.y, position.z, position.w));
       writer.append(String.format("plane: [%f %f %f %f], ", plane.x, plane.y, plane.z, plane.w));
       writer.append(String.format("atomIdx: %d, label: %d", atomIdx, label));
       writer.append(String.format(", padding0: %d, padding1: %d", padding0, padding1));
       writer.newLine();
     }
     // unbind buffers
     gl.glUnmapBuffer(GL_SHADER_STORAGE_BUFFER);
   }
 }
コード例 #21
0
 public Img3ElementHeader readImg3ElementHeader(ByteBuffer buffer) {
   Img3ElementHeader hdr = new Img3ElementHeader();
   hdr.signature = Img3ElementType.getType(buffer.getInt());
   hdr.full_size = buffer.getInt();
   hdr.data_size = buffer.getInt();
   return hdr;
 }
コード例 #22
0
 @Override
 public void fromBinary(final byte[] bytes) {
   final ByteBuffer buf = ByteBuffer.wrap(bytes);
   final int numSfcs = buf.getInt();
   final int numDimensions = buf.getInt();
   final int mappingSize = buf.getInt();
   maxEstimatedDuplicateIds = buf.getLong();
   maxEstimatedDuplicateIdsBigInteger = BigInteger.valueOf(maxEstimatedDuplicateIds);
   orderedSfcs = new SpaceFillingCurve[numSfcs];
   baseDefinitions = new NumericDimensionDefinition[numDimensions];
   for (int i = 0; i < numSfcs; i++) {
     final byte[] sfc = new byte[buf.getInt()];
     buf.get(sfc);
     orderedSfcs[i] = PersistenceUtils.fromBinary(sfc, SpaceFillingCurve.class);
   }
   for (int i = 0; i < numDimensions; i++) {
     final byte[] dim = new byte[buf.getInt()];
     buf.get(dim);
     baseDefinitions[i] = PersistenceUtils.fromBinary(dim, NumericDimensionDefinition.class);
   }
   final Builder<Integer, Byte> bimapBuilder = ImmutableBiMap.builder();
   for (int i = 0; i < mappingSize; i++) {
     bimapBuilder.put(Byte.valueOf(buf.get()).intValue(), buf.get());
   }
   orderedSfcIndexToTierId = bimapBuilder.build();
 }
コード例 #23
0
 /**
  * Create a roaring array based on a previously serialized ByteBuffer. As much as possible, the
  * ByteBuffer is used as the backend, however if you modify the content, the result is
  * unspecified.
  *
  * @param bb The source ByteBuffer
  */
 protected RoaringArray(ByteBuffer bb) {
   bb.order(ByteOrder.LITTLE_ENDIAN);
   if (bb.getInt() != SERIAL_COOKIE)
     throw new RuntimeException("I failed to find the right cookie.");
   this.size = bb.getInt();
   // we fully read the meta-data array to RAM, but the containers
   // themselves are memory-mapped
   this.array = new Element[this.size];
   final short keys[] = new short[this.size];
   final int cardinalities[] = new int[this.size];
   final boolean isBitmap[] = new boolean[this.size];
   for (int k = 0; k < this.size; ++k) {
     keys[k] = bb.getShort();
     cardinalities[k] = Util.toIntUnsigned(bb.getShort()) + 1;
     isBitmap[k] = cardinalities[k] > ArrayContainer.DEFAULT_MAX_SIZE;
   }
   for (int k = 0; k < this.size; ++k) {
     if (cardinalities[k] == 0) throw new RuntimeException("no");
     Container val;
     if (isBitmap[k]) {
       final LongBuffer bitmapArray = bb.asLongBuffer().slice();
       bitmapArray.limit(BitmapContainer.MAX_CAPACITY / 64);
       bb.position(bb.position() + BitmapContainer.MAX_CAPACITY / 8);
       val = new BitmapContainer(bitmapArray, cardinalities[k]);
     } else {
       final ShortBuffer shortArray = bb.asShortBuffer().slice();
       shortArray.limit(cardinalities[k]);
       bb.position(bb.position() + cardinalities[k] * 2);
       val = new ArrayContainer(shortArray, cardinalities[k]);
     }
     this.array[k] = new Element(keys[k], val);
   }
 }
コード例 #24
0
 /* (non-Javadoc)
  * @see org.exist.storage.log.Loggable#read(java.nio.ByteBuffer)
  */
 public void read(ByteBuffer in) {
   prevPage = in.getInt();
   pageNum = in.getInt();
   nextPage = in.getInt();
   oldPrev = in.getInt();
   oldNext = in.getInt();
 }
コード例 #25
0
ファイル: ChmItsfHeader.java プロジェクト: eoe2005/jchmweb
  public ChmItsfHeader(ByteBuffer bb) {
    byte[] sbuf = new byte[4];
    bb.get(sbuf);
    signature = new String(sbuf);

    version = bb.getInt();
    header_len = bb.getInt();
    unknown_000c = bb.getInt();
    last_modified = ByteBufferHelper.parseBigEndianInt(bb);
    Calendar c = Calendar.getInstance();
    c.set(1970, Calendar.JANUARY, 1);
    c.add(Calendar.SECOND, 0x3DB0C239);
    timestamp = c.getTime();
    // DateFormat f = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
    // System.out.println("Last modified: " + f.format(timestamp));

    lang_id = bb.getInt();
    bb.get(new byte[32]);
    unknown_len = bb.getLong();
    unknown_offset = bb.getLong();
    dir_offset = bb.getLong();
    dir_len = bb.getLong();
    data_offset = 0; // TODO:
    if (version >= 3) {
      data_offset = bb.getLong();
    }
  }
コード例 #26
0
  /** Populates the header with information received via socket */
  public void readHeader() throws IOException {
    if (this.socket != null) {
      final ByteBuffer cb = getCommBuffer();
      synchronized (cb) {
        fetchHeader();
        final int type = cb.getInt();
        final int numParts = cb.getInt();
        final int txid = cb.getInt();
        cb.clear();
        if (!MessageType.validate(type)) {
          throw new IOException(
              LocalizedStrings.ChunkedMessage_INVALID_MESSAGE_TYPE_0_WHILE_READING_HEADER
                  .toLocalizedString(Integer.valueOf(type)));
        }

        // Set the header and payload fields only after receiving all the
        // socket data, providing better message consistency in the face
        // of exceptional conditions (e.g. IO problems, timeouts etc.)
        this.msgType = type;
        this.numberOfParts = numParts; // Already set in setPayloadFields via setNumberOfParts
        this.transactionId = txid;
      }
    } else {
      throw new IOException(LocalizedStrings.ChunkedMessage_DEAD_CONNECTION.toLocalizedString());
    }
  }
コード例 #27
0
ファイル: Attachment.java プロジェクト: Rongmasihai/risecoin
 DigitalGoodsPurchase(ByteBuffer buffer, byte transactionVersion) {
   super(buffer, transactionVersion);
   this.goodsId = buffer.getLong();
   this.quantity = buffer.getInt();
   this.priceNQT = buffer.getLong();
   this.deliveryDeadlineTimestamp = buffer.getInt();
 }
コード例 #28
0
  /**
   * read the Header from the given ByteBuffer.
   *
   * @param bb ByteBuffer.
   * @throws Exception
   */
  public void read(ByteBuffer bb) throws Exception {
    // MAIN FILE HEADER
    bb.order(ByteOrder.BIG_ENDIAN);
    // magic number
    int SHP_MAGIC_read = bb.getInt(0);
    if (SHP_MAGIC_read != SHP_MAGIC) {
      throw new Exception("(ShapeFile) error: SHP_MAGIC = " + SHP_MAGIC + ", File: " + file);
    }
    // file length
    SHP_file_length = bb.getInt(24);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    int SHP_version_read = bb.getInt(28);
    if (SHP_version_read != SHP_VERSION) {
      throw new Exception("(ShapeFile) error: SHP_VERSION = " + SHP_VERSION + ", File: " + file);
    }

    SHP_shape_type = bb.getInt(32);

    try {
      shape_type = ShpShape.Type.byID(SHP_shape_type);
    } catch (Exception e) {
      e.printStackTrace();
    }

    SHP_bbox[0][0] = bb.getDouble(36); // x-min
    SHP_bbox[1][0] = bb.getDouble(44); // y-min
    SHP_bbox[0][1] = bb.getDouble(52); // x-max
    SHP_bbox[1][1] = bb.getDouble(60); // y-max
    SHP_bbox[2][1] = bb.getDouble(68); // z-min
    SHP_bbox[2][1] = bb.getDouble(76); // z-max
    SHP_range_m[0] = bb.getDouble(84); // m-min
    SHP_range_m[1] = bb.getDouble(92); // m-max

    bb.position(100);
  }
コード例 #29
0
ファイル: Zip64.java プロジェクト: BvbKoala/SourceCode
  /**
   * Parses the zip64 end of central directory record locator. The locator must be placed
   * immediately before the end of central directory (eocd) record starting at {@code eocdOffset}.
   *
   * <p>The position of the file cursor for {@code raf} after a call to this method is undefined an
   * callers must reposition it after each call to this method.
   */
  public static long parseZip64EocdRecordLocator(RandomAccessFile raf, long eocdOffset)
      throws IOException {
    // The spec stays curiously silent about whether a zip file with an EOCD record,
    // a zip64 locator and a zip64 eocd record is considered "empty". In our implementation,
    // we parse all records and read the counts from them instead of drawing any size or
    // layout based information.
    if (eocdOffset > ZIP64_LOCATOR_SIZE) {
      raf.seek(eocdOffset - ZIP64_LOCATOR_SIZE);
      if (Integer.reverseBytes(raf.readInt()) == ZIP64_LOCATOR_SIGNATURE) {
        byte[] zip64EocdLocator = new byte[ZIP64_LOCATOR_SIZE - 4];
        raf.readFully(zip64EocdLocator);
        ByteBuffer buf = ByteBuffer.wrap(zip64EocdLocator).order(ByteOrder.LITTLE_ENDIAN);

        final int diskWithCentralDir = buf.getInt();
        final long zip64EocdRecordOffset = buf.getLong();
        final int numDisks = buf.getInt();

        if (numDisks != 1 || diskWithCentralDir != 0) {
          throw new ZipException("Spanned archives not supported");
        }

        return zip64EocdRecordOffset;
      }
    }

    return -1;
  }
コード例 #30
0
ファイル: TCP.java プロジェクト: yuhaisheng1/coordinator
  @Override
  public IPacket deserialize(final byte[] data, final int offset, final int length) {
    final ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
    this.sourcePort = bb.getShort();
    this.destinationPort = bb.getShort();
    this.sequence = bb.getInt();
    this.acknowledge = bb.getInt();
    this.flags = bb.getShort();
    this.dataOffset = (byte) (this.flags >> 12 & 0xf);
    this.flags = (short) (this.flags & 0x1ff);
    this.windowSize = bb.getShort();
    this.checksum = bb.getShort();
    this.urgentPointer = bb.getShort();
    if (this.dataOffset > 5) {
      int optLength = (this.dataOffset << 2) - 20;
      if (bb.limit() < bb.position() + optLength) {
        optLength = bb.limit() - bb.position();
      }
      try {
        this.options = new byte[optLength];
        bb.get(this.options, 0, optLength);
      } catch (final IndexOutOfBoundsException e) {
        this.options = null;
      }
    }

    this.payload = new Data();
    this.payload = this.payload.deserialize(data, bb.position(), bb.limit() - bb.position());
    this.payload.setParent(this);
    return this;
  }