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

The following are Jave code examples for showing how to use limit() 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: jdk8u-jdk   File: SSLExplorer.java   View Source Code Vote up 6 votes
private static SSLCapabilities exploreHandshake(
        ByteBuffer input, byte recordMajorVersion,
        byte recordMinorVersion, int recordLength) throws IOException {

    // What is the handshake type?
    byte handshakeType = input.get();
    if (handshakeType != 0x01) {   // 0x01: client_hello message
        throw new IllegalStateException("Not initial handshaking");
    }

    // What is the handshake body length?
    int handshakeLength = getInt24(input);

    // Theoretically, a single handshake message might span multiple
    // records, but in practice this does not occur.
    if (handshakeLength > (recordLength - 4)) { // 4: handshake header size
        throw new SSLException("Handshake message spans multiple records");
    }

    input = input.duplicate();
    input.limit(handshakeLength + input.position());
    return exploreClientHello(input,
                                recordMajorVersion, recordMinorVersion);
}
 
Example 2
Project: web-perf-analyzer   File: HttpRequest.java   View Source Code Vote up 5 votes
/**
 * Write string to stream
 *
 * @param value
 * @return this stream
 * @throws IOException
 */
public RequestOutputStream write(final String value) throws IOException {
	final ByteBuffer bytes = encoder.encode(CharBuffer.wrap(value));

	super.write(bytes.array(), 0, bytes.limit());

	return this;
}
 
Example 3
Project: jdk8u-jdk   File: ISO_8859_1.java   View Source Code Vote up 5 votes
private CoderResult decodeArrayLoop(ByteBuffer src,
                                    CharBuffer dst)
{
    byte[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    char[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);

    try {
        while (sp < sl) {
            byte b = sa[sp];
            if (dp >= dl)
                return CoderResult.OVERFLOW;
            da[dp++] = (char)(b & 0xff);
            sp++;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 4
Project: openjdk-jdk10   File: DatagramChannelImpl.java   View Source Code Vote up 5 votes
private int send(FileDescriptor fd, ByteBuffer src, InetSocketAddress target)
    throws IOException
{
    if (src instanceof DirectBuffer)
        return sendFromNativeBuffer(fd, src, target);

    // Substitute a native buffer
    int pos = src.position();
    int lim = src.limit();
    assert (pos <= lim);
    int rem = (pos <= lim ? lim - pos : 0);

    ByteBuffer bb = Util.getTemporaryDirectBuffer(rem);
    try {
        bb.put(src);
        bb.flip();
        // Do not update src until we see how many bytes were written
        src.position(pos);

        int n = sendFromNativeBuffer(fd, bb, target);
        if (n > 0) {
            // now update src
            src.position(pos + n);
        }
        return n;
    } finally {
        Util.releaseTemporaryDirectBuffer(bb);
    }
}
 
Example 5
Project: jdk8u-jdk   File: ISO_8859_1.java   View Source Code Vote up 5 votes
private CoderResult encodeArrayLoop(CharBuffer src,
                                    ByteBuffer dst)
{
    char[] sa = src.array();
    int soff = src.arrayOffset();
    int sp = soff + src.position();
    int sl = soff + src.limit();
    assert (sp <= sl);
    sp = (sp <= sl ? sp : sl);
    byte[] da = dst.array();
    int doff = dst.arrayOffset();
    int dp = doff + dst.position();
    int dl = doff + dst.limit();
    assert (dp <= dl);
    dp = (dp <= dl ? dp : dl);
    int dlen = dl - dp;
    int slen = sl - sp;
    int len  = (dlen < slen) ? dlen : slen;
    try {
        int ret = encodeISOArray(sa, sp, da, dp, len);
        sp = sp + ret;
        dp = dp + ret;
        if (ret != len) {
            if (sgp.parse(sa[sp], sa, sp, sl) < 0)
                return sgp.error();
            return sgp.unmappableResult();
        }
        if (len < slen)
            return CoderResult.OVERFLOW;
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - soff);
        dst.position(dp - doff);
    }
}
 
Example 6
Project: OpenJSharp   File: SingleByteEncoder.java   View Source Code Vote up 5 votes
private CoderResult encodeArrayLoop(CharBuffer src, ByteBuffer dst) {
    char[] sa = src.array();
    int sp = src.arrayOffset() + src.position();
    int sl = src.arrayOffset() + src.limit();
    sp = (sp <= sl ? sp : sl);
    byte[] da = dst.array();
    int dp = dst.arrayOffset() + dst.position();
    int dl = dst.arrayOffset() + dst.limit();
    dp = (dp <= dl ? dp : dl);

    try {
        while (sp < sl) {
            char c = sa[sp];
            if (Surrogate.is(c)) {
                if (sgp.parse(c, sa, sp, sl) < 0)
                    return sgp.error();
                return sgp.unmappableResult();
            }
            if (c >= '\uFFFE')
                return CoderResult.unmappableForLength(1);
            if (dl - dp < 1)
                return CoderResult.OVERFLOW;

            char e = index2.charAt(index1[(c & mask1) >> shift]
                                   + (c & mask2));

            // If output byte is zero because input char is zero
            // then character is mappable, o.w. fail
            if (e == '\u0000' && c != '\u0000')
                return CoderResult.unmappableForLength(1);

            sp++;
            da[dp++] = (byte)e;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(sp - src.arrayOffset());
        dst.position(dp - dst.arrayOffset());
    }
}
 
Example 7
Project: OpenJSharp   File: ZipFileSystem.java   View Source Code Vote up 5 votes
final long readFullyAt(byte[] buf, int off, long len, long pos)
    throws IOException
{
    ByteBuffer bb = ByteBuffer.wrap(buf);
    bb.position(off);
    bb.limit((int)(off + len));
    return readFullyAt(bb, pos);
}
 
Example 8
Project: CustomWorldGen   File: VertexBuffer.java   View Source Code Vote up 5 votes
public void bufferData(ByteBuffer data)
{
    this.bindBuffer();
    OpenGlHelper.glBufferData(OpenGlHelper.GL_ARRAY_BUFFER, data, 35044);
    this.unbindBuffer();
    this.count = data.limit() / this.vertexFormat.getNextOffset();
}
 
Example 9
Project: ProyectoPacientes   File: StringUtils.java   View Source Code Vote up 5 votes
public static byte[] getBytesNullTerminated(String value, String encoding) throws UnsupportedEncodingException {
    Charset cs = findCharset(encoding);

    ByteBuffer buf = cs.encode(value);

    int encodedLen = buf.limit();
    byte[] asBytes = new byte[encodedLen + 1];
    buf.get(asBytes, 0, encodedLen);
    asBytes[encodedLen] = 0;

    return asBytes;
}
 
Example 10
Project: incubator-netbeans   File: Archive.java   View Source Code Vote up 5 votes
public @Override int hashCode() {
    ByteBuffer clone = master.duplicate();
    clone.position(offset+8);
    clone.limit(offset+8+master.getChar(offset+6));

    int code = 53*master.getChar(offset);
    while (clone.hasRemaining()) code = code*53 + clone.get();
    return code;
}
 
Example 11
Project: jdk8u-jdk   File: TrueTypeFont.java   View Source Code Vote up 5 votes
byte[] readBytes(int offset, int length) {
    ByteBuffer buffer = readBlock(offset, length);
    if (buffer.hasArray()) {
        return buffer.array();
    } else {
        byte[] bufferBytes = new byte[buffer.limit()];
        buffer.get(bufferBytes);
        return bufferBytes;
    }
}
 
Example 12
Project: openjdk-jdk10   File: ByteBuffers.java   View Source Code Vote up 4 votes
@Override
public void main(Provider p) throws Exception {
    if (p.getService("MessageDigest", "MD5") == null) {
        System.out.println("Provider does not support MD5, skipping");
        return;
    }

    Random random = new Random();
    int n = 10 * 1024;
    byte[] t = new byte[n];
    random.nextBytes(t);

    MessageDigest md = MessageDigest.getInstance("MD5", p);
    byte[] d1 = md.digest(t);

    // test 1: ByteBuffer with an accessible backing array
    ByteBuffer b1 = ByteBuffer.allocate(n + 256);
    b1.position(random.nextInt(256));
    b1.limit(b1.position() + n);
    ByteBuffer b2 = b1.slice();
    b2.put(t);
    b2.clear();
    byte[] d2 = digest(md, b2, random);
    if (Arrays.equals(d1, d2) == false) {
        throw new Exception("Test 1 failed");
    }

    // test 2: direct ByteBuffer
    ByteBuffer b3 = ByteBuffer.allocateDirect(t.length);
    b3.put(t);
    b3.clear();
    byte[] d3 = digest(md, b3, random);
    if (Arrays.equals(d1, d2) == false) {
        throw new Exception("Test 2 failed");
    }

    // test 3: ByteBuffer without an accessible backing array
    b2.clear();
    ByteBuffer b4 = b2.asReadOnlyBuffer();
    byte[] d4 = digest(md, b4, random);
    if (Arrays.equals(d1, d2) == false) {
        throw new Exception("Test 3 failed");
    }
    System.out.println("All tests passed");
}
 
Example 13
Project: fresco_floodlight   File: IPv4.java   View Source Code Vote up 4 votes
@Override
public IPacket deserialize(byte[] data, int offset, int length)
        throws PacketParsingException {
    ByteBuffer bb = ByteBuffer.wrap(data, offset, length);
    short sscratch;

    this.version = bb.get();
    this.headerLength = (byte) (this.version & 0xf);
    this.version = (byte) ((this.version >> 4) & 0xf);
    if (this.version != 4) {
        throw new PacketParsingException(
                "Invalid version for IPv4 packet: " +
                this.version);
    }
    this.diffServ = bb.get();
    this.totalLength = bb.getShort();
    this.identification = bb.getShort();
    sscratch = bb.getShort();
    this.flags = (byte) ((sscratch >> IPV4_FLAGS_SHIFT) & IPV4_FLAGS_MASK);
    this.fragmentOffset = (short) (sscratch & IPV4_OFFSET_MASK);
    this.ttl = bb.get();
    this.protocol = IpProtocol.of(U8.f(bb.get()));
    this.checksum = bb.getShort();
    this.sourceAddress = IPv4Address.of(bb.getInt());
    this.destinationAddress = IPv4Address.of(bb.getInt());

    if (this.headerLength > 5) {
        int optionsLength = (this.headerLength - 5) * 4;
        this.options = new byte[optionsLength];
        bb.get(this.options);
    }

    IPacket payload;
    isFragment = ((this.flags & IPV4_FLAGS_DONTFRAG) == 0) &&
            ((this.flags & IPV4_FLAGS_MOREFRAG) != 0 ||
            this.fragmentOffset != 0);
    if (!isFragment && IPv4.protocolClassMap.containsKey(this.protocol)) {
        Class<? extends IPacket> clazz = IPv4.protocolClassMap.get(this.protocol);
        try {
            payload = clazz.newInstance();
        } catch (Exception e) {
            throw new RuntimeException("Error parsing payload for IPv4 packet", e);
        }
    } else {
        if (log.isTraceEnabled() && isFragment) {
            log.trace("IPv4 fragment detected {}->{}, forward using IP header only",
                    this.sourceAddress.toString(),
                    this.destinationAddress.toString());
        }
        payload = new Data();
    }
    int payloadLength = this.totalLength - this.headerLength * 4;
    int remLength = bb.limit()-bb.position();
    if (remLength < payloadLength)
        payloadLength = bb.limit()-bb.position();
    this.payload = payload.deserialize(data, bb.position(), payloadLength);
    this.payload.setParent(this);

    if (this.totalLength > length)
        this.isTruncated = true;
    else
        this.isTruncated = false;

    return this;
}
 
Example 14
Project: apache-tomcat-7.0.73-with-comment   File: WsPongMessage.java   View Source Code Vote up 4 votes
public WsPongMessage(ByteBuffer applicationData) {
    byte[] dst = new byte[applicationData.limit()];
    applicationData.get(dst);
    this.applicationData = ByteBuffer.wrap(dst);
}
 
Example 15
Project: openjdk-jdk10   File: Encrypt.java   View Source Code Vote up 4 votes
private void combination_15(List<byte[]> results, int mode, byte[] AAD,
        byte[] plainText, AlgorithmParameters params) throws Exception {
    Cipher c = createCipher(mode, params);

    // prepare ByteBuffer1 to test
    ByteBuffer buf1 = ByteBuffer.allocateDirect(AAD.length / 2);
    buf1.put(AAD, 0, AAD.length / 2);
    buf1.position(0);
    buf1.limit(AAD.length / 2);

    // process the first half of AAD data
    c.updateAAD(buf1);

    // prepare ByteBuffer2 to test
    ByteBuffer buf2 = ByteBuffer.allocateDirect(
            AAD.length - AAD.length / 2);
    buf2.put(AAD, AAD.length / 2, AAD.length - AAD.length / 2);
    buf2.position(0);
    buf2.limit(AAD.length - AAD.length / 2);

    // process the rest of AAD data
    c.updateAAD(buf2);

    // prepare buffers to encrypt/decrypt
    ByteBuffer in = ByteBuffer.allocateDirect(plainText.length);
    in.put(plainText);
    in.position(0);
    in.limit(plainText.length);
    ByteBuffer output = ByteBuffer.allocateDirect(
            c.getOutputSize(in.limit()));
    output.position(0);
    output.limit(c.getOutputSize(in.limit()));

    // process input text
    c.doFinal(in, output);
    int resultSize = output.position();
    byte[] result15 = new byte[resultSize];
    output.position(0);
    output.limit(resultSize);
    output.get(result15, 0, resultSize);
    results.add(result15);
}
 
Example 16
Project: lazycat   File: WsOutbound.java   View Source Code Vote up 4 votes
/**
 * Writes the provided bytes as the payload in a new WebSocket frame.
 *
 * @param buffer
 *            The bytes to include in the payload.
 * @param finalFragment
 *            Do these bytes represent the final fragment of a WebSocket
 *            message?
 * @throws IOException
 */
private void doWriteBytes(ByteBuffer buffer, boolean finalFragment) throws IOException {

	if (closed) {
		throw new IOException(sm.getString("outbound.closed"));
	}

	// Work out the first byte
	int first = 0x00;
	if (finalFragment) {
		first = first + 0x80;
	}
	if (firstFrame) {
		if (text.booleanValue()) {
			first = first + 0x1;
		} else {
			first = first + 0x2;
		}
	}
	// Continuation frame is OpCode 0
	upgradeOutbound.write(first);

	if (buffer.limit() < 126) {
		upgradeOutbound.write(buffer.limit());
	} else if (buffer.limit() < 65536) {
		upgradeOutbound.write(126);
		upgradeOutbound.write(buffer.limit() >>> 8);
		upgradeOutbound.write(buffer.limit() & 0xFF);
	} else {
		// Will never be more than 2^31-1
		upgradeOutbound.write(127);
		upgradeOutbound.write(0);
		upgradeOutbound.write(0);
		upgradeOutbound.write(0);
		upgradeOutbound.write(0);
		upgradeOutbound.write(buffer.limit() >>> 24);
		upgradeOutbound.write(buffer.limit() >>> 16);
		upgradeOutbound.write(buffer.limit() >>> 8);
		upgradeOutbound.write(buffer.limit() & 0xFF);
	}

	// Write the content
	upgradeOutbound.write(buffer.array(), buffer.arrayOffset(), buffer.limit());
	upgradeOutbound.flush();

	// Reset
	if (finalFragment) {
		text = null;
		firstFrame = true;
	} else {
		firstFrame = false;
	}
	bb.clear();
}
 
Example 17
Project: feeyo-redisproxy   File: Connection.java   View Source Code Vote up 4 votes
private boolean write0() throws IOException {
	int written = 0;
	ByteBuffer buffer = writeBuffer;
	if (buffer != null) {	
		
		 //只要写缓冲记录中还有数据就不停写入,但如果写入字节为0,证明网络繁忙,则退出
		while (buffer.hasRemaining()) {
			written = channel.write(buffer);
			if (written > 0) {
				netOutBytes += written;
				lastWriteTime = TimeUtil.currentTimeMillis();
			} else {
				break;
			}
		}

		//如果写缓冲中还有数据证明网络繁忙,计数并退出,否则清空缓冲
		if (buffer.hasRemaining()) {
			writeAttempts++;
			return false;
		} else {
			writeBuffer = null;
			recycle( buffer );
		}
	}
	
	//读取缓存队列并写channel
	while ((buffer = writeQueue.poll()) != null) {
		if (buffer.limit() == 0) {
			recycle(buffer);
			close("quit send");
			return true;
		}

		buffer.flip();
		try {
			while (buffer.hasRemaining()) {
				written = channel.write(buffer);   // java.io.IOException:
												   // Connection reset by peer
				if (written > 0) {
					lastWriteTime = TimeUtil.currentTimeMillis();
					netOutBytes += written;
				} else {
					break;
				}
			}
		} catch (IOException e1) {
			recycle(buffer);
			throw e1;
		} 
		
		 //如果写缓冲中还有数据证明网络繁忙,计数,记录下这次未写完的数据到写缓冲记录并退出,否则回收缓冲
		if (buffer.hasRemaining()) {
			writeBuffer = buffer;
			writeAttempts++;
			return false;
		} else {
			recycle(buffer);
		}
	}
	return true;
}
 
Example 18
Project: grafika   File: CircularEncoder.java   View Source Code Vote up 4 votes
/**
 * Drains all pending output from the decoder, and adds it to the circular buffer.
 */
public void drainEncoder() {
    final int TIMEOUT_USEC = 0;     // no timeout -- check for buffers, bail if none

    ByteBuffer[] encoderOutputBuffers = mEncoder.getOutputBuffers();
    while (true) {
        int encoderStatus = mEncoder.dequeueOutputBuffer(mBufferInfo, TIMEOUT_USEC);
        if (encoderStatus == MediaCodec.INFO_TRY_AGAIN_LATER) {
            // no output available yet
            break;
        } else if (encoderStatus == MediaCodec.INFO_OUTPUT_BUFFERS_CHANGED) {
            // not expected for an encoder
            encoderOutputBuffers = mEncoder.getOutputBuffers();
        } else if (encoderStatus == MediaCodec.INFO_OUTPUT_FORMAT_CHANGED) {
            // Should happen before receiving buffers, and should only happen once.
            // The MediaFormat contains the csd-0 and csd-1 keys, which we'll need
            // for MediaMuxer.  It's unclear what else MediaMuxer might want, so
            // rather than extract the codec-specific data and reconstruct a new
            // MediaFormat later, we just grab it here and keep it around.
            mEncodedFormat = mEncoder.getOutputFormat();
            Log.d(TAG, "encoder output format changed: " + mEncodedFormat);
        } else if (encoderStatus < 0) {
            Log.w(TAG, "unexpected result from encoder.dequeueOutputBuffer: " +
                    encoderStatus);
            // let's ignore it
        } else {
            ByteBuffer encodedData = encoderOutputBuffers[encoderStatus];
            if (encodedData == null) {
                throw new RuntimeException("encoderOutputBuffer " + encoderStatus +
                        " was null");
            }

            if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_CODEC_CONFIG) != 0) {
                // The codec config data was pulled out when we got the
                // INFO_OUTPUT_FORMAT_CHANGED status.  The MediaMuxer won't accept
                // a single big blob -- it wants separate csd-0/csd-1 chunks --
                // so simply saving this off won't work.
                if (VERBOSE) Log.d(TAG, "ignoring BUFFER_FLAG_CODEC_CONFIG");
                mBufferInfo.size = 0;
            }

            if (mBufferInfo.size != 0) {
                // adjust the ByteBuffer values to match BufferInfo (not needed?)
                encodedData.position(mBufferInfo.offset);
                encodedData.limit(mBufferInfo.offset + mBufferInfo.size);

                mEncBuffer.add(encodedData, mBufferInfo.flags,
                        mBufferInfo.presentationTimeUs);

                if (VERBOSE) {
                    Log.d(TAG, "sent " + mBufferInfo.size + " bytes to muxer, ts=" +
                            mBufferInfo.presentationTimeUs);
                }
            }

            mEncoder.releaseOutputBuffer(encoderStatus, false);

            if ((mBufferInfo.flags & MediaCodec.BUFFER_FLAG_END_OF_STREAM) != 0) {
                Log.w(TAG, "reached end of stream unexpectedly");
                break;      // out of while
            }
        }
    }
}
 
Example 19
Project: ApkMultiChannelPlugin   File: CentralDirectoryRecord.java   View Source Code Vote up 4 votes
public static CentralDirectoryRecord createWithDeflateCompressedData(
        String name,
        int lastModifiedTime,
        int lastModifiedDate,
        long crc32,
        long compressedSize,
        long uncompressedSize,
        long localFileHeaderOffset) {
    byte[] nameBytes = name.getBytes(StandardCharsets.UTF_8);
    int recordSize = HEADER_SIZE_BYTES + nameBytes.length;
    ByteBuffer result = ByteBuffer.allocate(recordSize);
    result.order(ByteOrder.LITTLE_ENDIAN);
    result.putInt(RECORD_SIGNATURE);
    ZipUtils.putUnsignedInt16(result, 0x14); // Version made by
    ZipUtils.putUnsignedInt16(result, 0x14); // Minimum version needed to extract
    result.putShort(ZipUtils.GP_FLAG_EFS); // UTF-8 character encoding used for entry name
    result.putShort(ZipUtils.COMPRESSION_METHOD_DEFLATED);
    ZipUtils.putUnsignedInt16(result, lastModifiedTime);
    ZipUtils.putUnsignedInt16(result, lastModifiedDate);
    ZipUtils.putUnsignedInt32(result, crc32);
    ZipUtils.putUnsignedInt32(result, compressedSize);
    ZipUtils.putUnsignedInt32(result, uncompressedSize);
    ZipUtils.putUnsignedInt16(result, nameBytes.length);
    ZipUtils.putUnsignedInt16(result, 0); // Extra field length
    ZipUtils.putUnsignedInt16(result, 0); // File comment length
    ZipUtils.putUnsignedInt16(result, 0); // Disk number
    ZipUtils.putUnsignedInt16(result, 0); // Internal file attributes
    ZipUtils.putUnsignedInt32(result, 0); // External file attributes
    ZipUtils.putUnsignedInt32(result, localFileHeaderOffset);
    result.put(nameBytes);

    if (result.hasRemaining()) {
        throw new RuntimeException("pos: " + result.position() + ", limit: " + result.limit());
    }
    result.flip();
    return new CentralDirectoryRecord(
            result,
            lastModifiedTime,
            lastModifiedDate,
            crc32,
            compressedSize,
            uncompressedSize,
            localFileHeaderOffset,
            name,
            nameBytes.length);
}
 
Example 20
Project: openjdk-jdk10   File: PerfStringCounter.java   View Source Code Vote up 4 votes
PerfStringCounter(String name, Variability v,
                  int flags, ByteBuffer bb) {
    this(name, v, flags, bb.limit(), bb);
}