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

The following are Jave code examples for showing how to use mark() 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: defense-solutions-proofs-of-concept   File: CoTAdapter.java   View Source Code Vote up 6 votes
@Override
public void receive(ByteBuffer buf, String channelId)
{
	buf.mark();
	int size = buf.remaining();
	if (size < 1)
		return;
	byte[] data = new byte[size];
	buf.get(data, 0, size);
	//System.out.println(" \n");
	//System.out.println("Read " + size + " bytes");

	String xml = new String(data);
	parseUsingDocument(xml,channelId);
	//parseUsingStream(buf);
}
 
Example 2
Project: Responder-Android   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 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: CloseFrameBuilder.java   View Source Code Vote up 6 votes
private void initCloseCode() throws InvalidFrameException {
    code = CloseFrame.NOCODE;
    ByteBuffer payload = super.getPayloadData();
    payload.mark();
    if (payload.remaining() >= 2) {
        ByteBuffer bb = ByteBuffer.allocate(4);
        bb.position(2);
        bb.putShort(payload.getShort());
        bb.position(0);
        code = bb.getInt();

        if (code == CloseFrame.ABNORMAL_CLOSE || code == CloseFrame.TLS_ERROR || code == CloseFrame.NOCODE || code > 4999 || code < 1000 || code == 1004) {
            throw new InvalidFrameException("closecode must not be sent over the wire: " + code);
        }
    }
    payload.reset();
}
 
Example 5
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 6
Project: Quavo   File: CacheDefragmenter.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws IOException {
	try (FileStore in = FileStore.open(Constants.CACHE_PATH)) {
		try (FileStore out = FileStore.create(Constants.CACHETMP_PATH, in.getTypeCount())) {
			for (int type = 0; type < in.getTypeCount(); type++) {
				ByteBuffer buf = in.read(255, type);
				buf.mark();
				out.write(255, type, buf);
				buf.reset();

				ReferenceTable rt = ReferenceTable.decode(Container.decode(buf).getData());
				for (int file = 0; file < rt.capacity(); file++) {
					if (rt.getEntry(file) == null) {
						System.out.println(type + ", " + file);
						continue;
					}

					out.write(type, file, in.read(type, file));
				}
			}
		}
	}
}
 
Example 7
Project: Responder-Android   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 8
Project: boutique-de-jus   File: Event.java   View Source Code Vote up 5 votes
private static int findPositionOf(final ByteBuffer buf, final int stop) {

        buf.mark();
        skipUntil(buf, stop);
        int pos = buf.position();
        buf.reset();
        return pos;
    }
 
Example 9
Project: openjdk-jdk10   File: Http2Connection.java   View Source Code Vote up 5 votes
private static String toHexdump1(ByteBuffer bb) {
    bb.mark();
    StringBuilder sb = new StringBuilder(512);
    Formatter f = new Formatter(sb);

    while (bb.hasRemaining()) {
        int i =  Byte.toUnsignedInt(bb.get());
        f.format("%02x:", i);
    }
    sb.deleteCharAt(sb.length()-1);
    bb.reset();
    return sb.toString();
}
 
Example 10
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 11
Project: jdk8u-jdk   File: SameBuffer.java   View Source Code Vote up 5 votes
private void runGCMWithSeparateBuffers(int mode, ByteBuffer buffer,
        ByteBuffer textBB, int txtOffset, int dataLength,
        AlgorithmParameters params) throws Exception {
    // take offset into account
    textBB.position(txtOffset);
    textBB.mark();

    // first, generate the cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(buffer);
    buffer.flip();
    ByteBuffer outBB = ByteBuffer.allocateDirect(
            cipher.getOutputSize(dataLength));

    cipher.doFinal(textBB, outBB);// get cipher text in outBB
    outBB.flip();

    // restore positions
    textBB.reset();

    // next, generate cipher text again in a buffer that shares content
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(buffer);
    buffer.flip();
    ByteBuffer buf2 = textBB.duplicate(); // buf2 shares textBuf context
    buf2.limit(txtOffset + anotherCipher.getOutputSize(dataLength));
    int dataProcessed2 = anotherCipher.doFinal(textBB, buf2);
    buf2.position(txtOffset);
    buf2.limit(txtOffset + dataProcessed2);

    if (!buf2.equals(outBB)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example 12
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 13
Project: hadoop-oss   File: DataChecksum.java   View Source Code Vote up 5 votes
/**
 * Calculate checksums for 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 checksum.
 * @param checksums the DirectByteBuffer into which checksums will be
 *                  stored. Enough space must be available in this
 *                  buffer to put the checksums.
 */
public void calculateChunkedSums(ByteBuffer data, ByteBuffer checksums) {
  if (type.size == 0) return;
  
  if (data.hasArray() && checksums.hasArray()) {
    calculateChunkedSums(data.array(), data.arrayOffset() + data.position(), data.remaining(),
        checksums.array(), checksums.arrayOffset() + checksums.position());
    return;
  }

  if (NativeCrc32.isAvailable()) {
    NativeCrc32.calculateChunkedSums(bytesPerChecksum, type.id,
        checksums, data);
    return;
  }
  
  data.mark();
  checksums.mark();
  try {
    byte[] buf = new byte[bytesPerChecksum];
    while (data.remaining() > 0) {
      int n = Math.min(data.remaining(), bytesPerChecksum);
      data.get(buf, 0, n);
      summer.reset();
      summer.update(buf, 0, n);
      checksums.putInt((int)summer.getValue());
    }
  } finally {
    data.reset();
    checksums.reset();
  }
}
 
Example 14
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 15
Project: openjdk-jdk10   File: SameBuffer.java   View Source Code Vote up 5 votes
private void runGCMWithSeparateBuffers(int mode, ByteBuffer buffer,
        ByteBuffer textBB, int txtOffset, int dataLength,
        AlgorithmParameters params) throws Exception {
    // take offset into account
    textBB.position(txtOffset);
    textBB.mark();

    // first, generate the cipher text at an allocated buffer
    Cipher cipher = createCipher(mode, params);
    cipher.updateAAD(buffer);
    buffer.flip();
    ByteBuffer outBB = ByteBuffer.allocateDirect(
            cipher.getOutputSize(dataLength));

    cipher.doFinal(textBB, outBB);// get cipher text in outBB
    outBB.flip();

    // restore positions
    textBB.reset();

    // next, generate cipher text again in a buffer that shares content
    Cipher anotherCipher = createCipher(mode, params);
    anotherCipher.updateAAD(buffer);
    buffer.flip();
    ByteBuffer buf2 = textBB.duplicate(); // buf2 shares textBuf context
    buf2.limit(txtOffset + anotherCipher.getOutputSize(dataLength));
    int dataProcessed2 = anotherCipher.doFinal(textBB, buf2);
    buf2.position(txtOffset);
    buf2.limit(txtOffset + dataProcessed2);

    if (!buf2.equals(outBB)) {
        throw new RuntimeException(
                "Two results are not equal, mode:" + mode);
    }
}
 
Example 16
Project: Responder-Android   File: Draft_75.java   View Source Code Vote up 5 votes
protected List<Framedata> translateRegularFrame( ByteBuffer buffer ) throws InvalidDataException {

		while ( buffer.hasRemaining() ) {
			byte newestByte = buffer.get();
			if( newestByte == START_OF_FRAME ) { // Beginning of Frame
				if( readingState )
					throw new InvalidFrameException( "unexpected START_OF_FRAME" );
				readingState = true;
			} else if( newestByte == END_OF_FRAME ) { // End of Frame
				if( !readingState )
					throw new InvalidFrameException( "unexpected END_OF_FRAME" );
				// 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 ) {
					currentFrame.flip();
					FramedataImpl1 curframe = new FramedataImpl1();
					curframe.setPayload( currentFrame );
					curframe.setFin( true );
					curframe.setOptcode( Opcode.TEXT );
					readyframes.add( curframe );
					this.currentFrame = null;
					buffer.mark();
				}
				readingState = false;
			} else if( readingState ) { // Regular frame data, add to current frame buffer //TODO This code is very expensive and slow
				if( currentFrame == null ) {
					currentFrame = createBuffer();
				} else if( !currentFrame.hasRemaining() ) {
					currentFrame = increaseBuffer( currentFrame );
				}
				currentFrame.put( newestByte );
			} else {
				return null;
			}
		}

		// if no error occurred this block will be reached
		/*if( readingState ) {
			checkAlloc(currentFrame.position()+1);
		}*/

		List<Framedata> frames = readyframes;
		readyframes = new LinkedList<Framedata>();
		return frames;
	}
 
Example 17
Project: monarch   File: Bytes.java   View Source Code Vote up 5 votes
/**
 * This method will convert the remaining bytes of an
 * encoded byte buffer into a string of the given charset.
 *
 * @param buf Encoded byte buffer.
 * @param charset Charset of the string encoded in the byte buffer.
 * @return String made from <code>buf</code> or null
 */
public static String toString(ByteBuffer buf, Charset charset) {
    if (buf == null) {
        return null;
    }
    buf.mark();
    String s = charset.decode(buf).toString();
    buf.reset();
    return s;
}
 
Example 18
Project: Responder-Android   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 19
Project: boohee_v5.6   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);
    try {
        bytes.mark();
        String s = decode.decode(bytes).toString();
        bytes.reset();
        return s;
    } catch (Throwable e) {
        throw new InvalidDataException((int) CloseFrame.NO_UTF8, e);
    }
}
 
Example 20
Project: abhot   File: DataPointsRowKeySerializer.java   View Source Code Vote up 4 votes
@Override
public DataPointsRowKey fromByteBuffer(ByteBuffer byteBuffer)
{
	int start = byteBuffer.position();
	byteBuffer.mark();
	//Find null
	while (byteBuffer.get() != 0x0);

	int nameSize = (byteBuffer.position() - start) -1;
	byteBuffer.reset();

	byte[] metricName = new byte[nameSize];
	byteBuffer.get(metricName);
	byteBuffer.get(); //Skip the null

	long timestamp = byteBuffer.getLong();

	//Check for datatype marker which ia a null
	byteBuffer.mark();
	//default to legacy type
	String dataType = LegacyDataPointFactory.DATASTORE_TYPE;
	if (byteBuffer.get() == 0x0)
	{
		int dtSize = byteBuffer.get();
		byte[] dataTypeBytes = new byte[dtSize];
		byteBuffer.get(dataTypeBytes);
		dataType = new String(dataTypeBytes, UTF8);
	}
	else
	{
		byteBuffer.reset();
	}

	DataPointsRowKey rowKey = new DataPointsRowKey(getString(new String(metricName, UTF8)),
			timestamp, dataType);

	byte[] tagString = new byte[byteBuffer.remaining()];
	byteBuffer.get(tagString);

	String tags = new String(tagString, UTF8);

	extractTags(rowKey, tags);

	return rowKey;
}