Java Code Examples for java.nio.ByteBuffer.reset()

The following are Jave code examples for showing how to use reset() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: OpenJSharp   File: ISO2022.java   View Source Code Vote up 6 votes
private int findDesigBuf(ByteBuffer in, byte[][] desigs) {
    if (desigs == null) return -1;
    int i = 0;
    while (i < desigs.length) {
        if (desigs[i] != null && in.remaining() >= desigs[i].length) {
            int j = 0;
            in.mark();
            while (j < desigs[i].length && in.get() == desigs[i][j]) { j++; }
            if (j == desigs[i].length)
                return i;
            in.reset();
        }
        i++;
    }
    return -1;
}
 
Example 2
Project: boohee_v5.6   File: h.java   View Source Code Vote up 6 votes
public List<com.meiqia.core.a.a.d.d> c(ByteBuffer byteBuffer) {
    byteBuffer.mark();
    List<com.meiqia.core.a.a.d.d> e = super.e(byteBuffer);
    if (e == null) {
        byteBuffer.reset();
        e = this.g;
        this.f = true;
        if (this.h == null) {
            this.h = ByteBuffer.allocate(2);
            if (byteBuffer.remaining() > this.h.remaining()) {
                throw new com.meiqia.core.a.a.c.c();
            }
            this.h.put(byteBuffer);
            if (this.h.hasRemaining()) {
                this.g = new LinkedList();
            } else if (Arrays.equals(this.h.array(), j)) {
                e.add(new com.meiqia.core.a.a.d.b(1000));
            } else {
                throw new com.meiqia.core.a.a.c.c();
            }
        }
        throw new com.meiqia.core.a.a.c.c();
    }
    return e;
}
 
Example 3
Project: hadoop-oss   File: Text.java   View Source Code Vote up 6 votes
/**
 * Returns the next code point at the current position in
 * the buffer. The buffer's position will be incremented.
 * Any mark set on this buffer will be changed by this method!
 */
public static int bytesToCodePoint(ByteBuffer bytes) {
  bytes.mark();
  byte b = bytes.get();
  bytes.reset();
  int extraBytesToRead = bytesFromUTF8[(b & 0xFF)];
  if (extraBytesToRead < 0) return -1; // trailing byte!
  int ch = 0;

  switch (extraBytesToRead) {
  case 5: ch += (bytes.get() & 0xFF); ch <<= 6; /* remember, illegal UTF-8 */
  case 4: ch += (bytes.get() & 0xFF); ch <<= 6; /* remember, illegal UTF-8 */
  case 3: ch += (bytes.get() & 0xFF); ch <<= 6;
  case 2: ch += (bytes.get() & 0xFF); ch <<= 6;
  case 1: ch += (bytes.get() & 0xFF); ch <<= 6;
  case 0: ch += (bytes.get() & 0xFF);
  }
  ch -= offsetsFromUTF8[extraBytesToRead];

  return ch;
}
 
Example 4
Project: quorrabot   File: WebSocketImpl.java   View Source Code Vote up 6 votes
private HandshakeState isFlashEdgeCase(ByteBuffer request) throws IncompleteHandshakeException {
    request.mark();
    if (request.limit() > Draft.FLASH_POLICY_REQUEST.length) {
        return HandshakeState.NOT_MATCHED;
    } else if (request.limit() < Draft.FLASH_POLICY_REQUEST.length) {
        throw new IncompleteHandshakeException(Draft.FLASH_POLICY_REQUEST.length);
    } else {

        for (int flash_policy_index = 0; request.hasRemaining(); flash_policy_index++) {
            if (Draft.FLASH_POLICY_REQUEST[flash_policy_index] != request.get()) {
                request.reset();
                return HandshakeState.NOT_MATCHED;
            }
        }
        return HandshakeState.MATCHED;
    }
}
 
Example 5
Project: hadoop-oss   File: TestCoderBase.java   View Source Code Vote up 6 votes
/**
 * Clone chunk along with copying the associated data. It respects how the
 * chunk buffer is allocated, direct or non-direct. It avoids affecting the
 * original chunk.
 * @param chunk
 * @return a new chunk
 */
protected ECChunk cloneChunkWithData(ECChunk chunk) {
  if (chunk == null) {
    return null;
  }

  ByteBuffer srcBuffer = chunk.getBuffer();

  byte[] bytesArr = new byte[srcBuffer.remaining()];
  srcBuffer.mark();
  srcBuffer.get(bytesArr, 0, bytesArr.length);
  srcBuffer.reset();

  ByteBuffer destBuffer = allocateOutputBuffer(bytesArr.length);
  int pos = destBuffer.position();
  destBuffer.put(bytesArr);
  destBuffer.flip();
  destBuffer.position(pos);

  return new ECChunk(destBuffer);
}
 
Example 6
Project: quorrabot   File: Draft_75.java   View Source Code Vote up 6 votes
@Override
public ByteBuffer createBinaryFrame(Framedata framedata) {
    if (framedata.getOpcode() != Opcode.TEXT) {
        throw new RuntimeException("only text frames supported");
    }

    ByteBuffer pay = framedata.getPayloadData();
    ByteBuffer b = ByteBuffer.allocate(pay.remaining() + 2);
    b.put(START_OF_FRAME);
    pay.mark();
    b.put(pay);
    pay.reset();
    b.put(END_OF_FRAME);
    b.flip();
    return b;
}
 
Example 7
Project: kafka-0.11.0.0-src-with-comment   File: Utils.java   View Source Code Vote up 5 votes
/**
 * Read a buffer into a Byte array for the given offset and length
 */
public static byte[] readBytes(ByteBuffer buffer, int offset, int length) {
    byte[] dest = new byte[length];
    if (buffer.hasArray()) {
        System.arraycopy(buffer.array(), buffer.arrayOffset() + offset, dest, 0, length);
    } else {
        buffer.mark();
        buffer.position(offset);
        buffer.get(dest, 0, length);
        buffer.reset();
    }
    return dest;
}
 
Example 8
Project: apkfile   File: XmlStartElementChunk.java   View Source Code Vote up 5 votes
private void parseAttributes(ByteBuffer buffer) {
    int offset = this.offset + getHeaderSize() + attributeStart;
    int endOffset = offset + XmlAttribute.SIZE * attributeCount;
    buffer.mark();
    buffer.position(offset);
    while (offset < endOffset) {
        XmlAttribute attribute = XmlAttribute.create(buffer, this);
        nameIndexToAttribute.put(attribute.nameIndex(), attribute);
        offset += XmlAttribute.SIZE;
    }
    buffer.reset();
}
 
Example 9
Project: jchmlib   File: LZXInflator.java   View Source Code Vote up 5 votes
private void doIntelE8Decoding(ByteBuffer outBuf) {
    long curPos = intelCurPos;
    long fileSize = intelFileSize;

    outBuf.mark();
    while (outBuf.position() < outBuf.limit() - 10) {
        int b = outBuf.get() & 0xff;
        if (b != 0xe8) {
            curPos++;
            continue;
        }

        int markedOutBufPos = outBuf.position();

        // get UInt32
        int tmp = outBuf.getInt();
        long absoluteOffset = tmp & 0x00000000ffffffffL;

        if ((absoluteOffset >= -curPos) && (absoluteOffset < fileSize)) {
            long relativeOffset;
            if (absoluteOffset >= 0) {
                relativeOffset = absoluteOffset - curPos;
            } else {
                relativeOffset = absoluteOffset + fileSize;
            }
            outBuf.position(markedOutBufPos);
            outBuf.put((byte) (relativeOffset & 0xFF));
            outBuf.put((byte) ((relativeOffset >>> 8) & 0xFF));
            outBuf.put((byte) ((relativeOffset >>> 16) & 0xFF));
            outBuf.put((byte) ((relativeOffset >>> 24) & 0xFF));
        }
        curPos += 5;
    }
    outBuf.reset();
}
 
Example 10
Project: boohee_v5.6   File: g.java   View Source Code Vote up 5 votes
public ByteBuffer a(d dVar) {
    if (dVar.f() != e.TEXT) {
        throw new RuntimeException("only text frames supported");
    }
    ByteBuffer c = dVar.c();
    ByteBuffer allocate = ByteBuffer.allocate(c.remaining() + 2);
    allocate.put((byte) 0);
    c.mark();
    allocate.put(c);
    c.reset();
    allocate.put((byte) -1);
    allocate.flip();
    return allocate;
}
 
Example 11
Project: quorrabot   File: Draft_76.java   View Source Code Vote up 5 votes
@Override
public List<Framedata> translateFrame(ByteBuffer buffer) throws InvalidDataException {
    buffer.mark();
    List<Framedata> frames = super.translateRegularFrame(buffer);
    if (frames == null) {
        buffer.reset();
        frames = readyframes;
        readingState = true;
        if (currentFrame == null) {
            currentFrame = ByteBuffer.allocate(2);
        } else {
            throw new InvalidFrameException();
        }
        if (buffer.remaining() > currentFrame.remaining()) {
            throw new InvalidFrameException();
        } else {
            currentFrame.put(buffer);
        }
        if (!currentFrame.hasRemaining()) {
            if (Arrays.equals(currentFrame.array(), closehandshake)) {
                frames.add(new CloseFrameBuilder(CloseFrame.NORMAL));
                return frames;
            } else {
                throw new InvalidFrameException();
            }
        } else {
            readyframes = new LinkedList<Framedata>();
            return frames;
        }
    } else {
        return frames;
    }
}
 
Example 12
Project: hadoop-oss   File: TestDataChecksum.java   View Source Code Vote up 5 votes
private static ByteBuffer directify(ByteBuffer dataBuf) {
  ByteBuffer newBuf = ByteBuffer.allocateDirect(dataBuf.capacity());
  newBuf.position(dataBuf.position());
  newBuf.mark();
  newBuf.put(dataBuf);
  newBuf.reset();
  newBuf.limit(dataBuf.limit());
  return newBuf;
}
 
Example 13
Project: android-chunk-utils   File: XmlResourceMapChunk.java   View Source Code Vote up 5 votes
private List<Integer> enumerateResources(ByteBuffer buffer) {
  int resourceCount = (getOriginalChunkSize() - getHeaderSize()) / RESOURCE_SIZE;
  List<Integer> result = new ArrayList<>(resourceCount);
  int offset = this.offset + getHeaderSize();
  buffer.mark();
  buffer.position(offset);

  for (int i = 0; i < resourceCount; ++i) {
    result.add(buffer.getInt());
  }

  buffer.reset();
  return result;
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: TestEncodingDecoding.java   View Source Code Vote up 5 votes
@Override
public boolean willDecode(ByteBuffer bb) {
    bb.mark();
    if (bb.get() == 0x12 && bb.get() == 0x34) {
        return true;
    }
    bb.reset();
    return false;
}
 
Example 15
Project: quorrabot   File: Charsetfunctions.java   View Source Code Vote up 5 votes
public static String stringUtf8(ByteBuffer bytes) throws InvalidDataException {
    CharsetDecoder decode = Charset.forName("UTF8").newDecoder();
    decode.onMalformedInput(codingErrorAction);
    decode.onUnmappableCharacter(codingErrorAction);
    // decode.replaceWith( "X" );
    String s;
    try {
        bytes.mark();
        s = decode.decode(bytes).toString();
        bytes.reset();
    } catch (CharacterCodingException e) {
        throw new InvalidDataException(CloseFrame.NO_UTF8, e);
    }
    return s;
}
 
Example 16
Project: AndResM   File: XmlStartElementChunk.java   View Source Code Vote up 5 votes
private List<XmlAttribute> enumerateAttributes(ByteBuffer buffer) {
  List<XmlAttribute> result = new ArrayList<>(attributeCount);
  int offset = this.offset + getHeaderSize() + attributeStart;
  int endOffset = offset + XmlAttribute.SIZE * attributeCount;
  buffer.mark();
  buffer.position(offset);

  while (offset < endOffset) {
    result.add(XmlAttribute.create(buffer, this));
    offset += XmlAttribute.SIZE;
  }

  buffer.reset();
  return result;
}
 
Example 17
Project: quorrabot   File: FramedataImpl1.java   View Source Code Vote up 5 votes
@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();
}
 
Example 18
Project: hadoop   File: DataChecksum.java   View Source Code Vote up 4 votes
/**
 * Verify that the given checksums match the given data.
 * 
 * The 'mark' of the ByteBuffer parameters may be modified by this function,.
 * but the position is maintained.
 *  
 * @param data the DirectByteBuffer pointing to the data to verify.
 * @param checksums the DirectByteBuffer pointing to a series of stored
 *                  checksums
 * @param fileName the name of the file being read, for error-reporting
 * @param basePos the file position to which the start of 'data' corresponds
 * @throws ChecksumException if the checksums do not match
 */
public void verifyChunkedSums(ByteBuffer data, ByteBuffer checksums,
    String fileName, long basePos)
throws ChecksumException {
  if (type.size == 0) return;
  
  if (data.hasArray() && checksums.hasArray()) {
    verifyChunkedSums(
        data.array(), data.arrayOffset() + data.position(), data.remaining(),
        checksums.array(), checksums.arrayOffset() + checksums.position(),
        fileName, basePos);
    return;
  }
  if (NativeCrc32.isAvailable()) {
    NativeCrc32.verifyChunkedSums(bytesPerChecksum, type.id, checksums, data,
        fileName, basePos);
    return;
  }
  
  int startDataPos = data.position();
  data.mark();
  checksums.mark();
  try {
    byte[] buf = new byte[bytesPerChecksum];
    byte[] sum = new byte[type.size];
    while (data.remaining() > 0) {
      int n = Math.min(data.remaining(), bytesPerChecksum);
      checksums.get(sum);
      data.get(buf, 0, n);
      summer.reset();
      summer.update(buf, 0, n);
      int calculated = (int)summer.getValue();
      int stored = (sum[0] << 24 & 0xff000000) |
        (sum[1] << 16 & 0xff0000) |
        (sum[2] << 8 & 0xff00) |
        sum[3] & 0xff;
      if (calculated != stored) {
        long errPos = basePos + data.position() - startDataPos - n;
        throw new ChecksumException(
            "Checksum error: "+ fileName + " at "+ errPos +
            " exp: " + stored + " got: " + calculated, errPos);
      }
    }
  } finally {
    data.reset();
    checksums.reset();
  }
}
 
Example 19
Project: Quavo   File: Cache.java   View Source Code Vote up 4 votes
/**
 * Writes a file to the cache and updates the {@link ReferenceTable} that it is associated with.
 * 
 * @param type The type of file.
 * @param file The file id.
 * @param container The {@link Container} to write.
 * @param keys The encryption keys.
 * @throws IOException if an I/O error occurs.
 */
public void write(int type, int file, Container container, int[] keys) throws IOException {
	/* we don't want people reading/manipulating these manually */
	if (type == 255)
		throw new IOException("Reference tables can only be modified with the low level FileStore API!");

	/* increment the container's version */
	container.setVersion(container.getVersion()/* + 1 */);

	/* decode the reference table for this index */
	Container tableContainer = Container.decode(store.read(255, type));
	ReferenceTable table = ReferenceTable.decode(tableContainer.getData());

	/* grab the bytes we need for the checksum */
	ByteBuffer buffer = container.encode(keys);
	byte[] bytes = new byte[buffer.limit() - 2]; // last two bytes are the
													// version and shouldn't
													// be included
	buffer.mark();
	try {
		buffer.position(0);
		buffer.get(bytes, 0, bytes.length);
	} finally {
		buffer.reset();
	}

	/* calculate the new CRC checksum */
	CRC32 crc = new CRC32();
	crc.update(bytes, 0, bytes.length);

	/* update the version and checksum for this file */
	ReferenceTable.Entry entry = table.getEntry(file);
	if (entry == null) {
		/* create a new entry for the file */
		entry = new ReferenceTable.Entry(file);
		table.putEntry(file, entry);
	}
	entry.setVersion(container.getVersion());
	entry.setCrc((int) crc.getValue());

	/* calculate and update the whirlpool digest if we need to */
	if ((table.getFlags() & ReferenceTable.FLAG_WHIRLPOOL) != 0) {
		byte[] whirlpool = Whirlpool.whirlpool(bytes, 0, bytes.length);
		entry.setWhirlpool(whirlpool);
	}

	/* update the reference table version */
	table.setVersion(table.getVersion()/* + 1 */);

	/* save the reference table */
	tableContainer = new Container(tableContainer.getType(), table.encode());
	store.write(255, type, tableContainer.encode());

	/* save the file itself */
	store.write(type, file, buffer);
}
 
Example 20
Project: Quavo   File: FileStore.java   View Source Code Vote up 4 votes
/**
 * Writes a file.
 * 
 * @param type The type of the file.
 * @param id The id of the file.
 * @param data A {@link ByteBuffer} containing the contents of the file.
 * @throws IOException if an I/O error occurs.
 */
public void write(int type, int id, ByteBuffer data) throws IOException {
	data.mark();
	if (!write(type, id, data, true)) {
		data.reset();
		write(type, id, data, false);
	}
}