Java Code Examples for java.nio.ByteBuffer#remaining()

The following examples show how to use java.nio.ByteBuffer#remaining() . These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: Bytecoder   File: CertificateRequest.java    License: Apache License 2.0 6 votes vote down vote up
T13CertificateRequestMessage(HandshakeContext handshakeContext,
        ByteBuffer m) throws IOException {
    super(handshakeContext);

    // struct {
    //      opaque certificate_request_context<0..2^8-1>;
    //      Extension extensions<2..2^16-1>;
    //  } CertificateRequest;
    if (m.remaining() < 5) {
        throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER,
                "Invalid CertificateRequest handshake message: " +
                "no sufficient data");
    }
    this.requestContext = Record.getBytes8(m);

    if (m.remaining() < 4) {
        throw handshakeContext.conContext.fatal(Alert.ILLEGAL_PARAMETER,
                "Invalid CertificateRequest handshake message: " +
                "no sufficient extensions data");
    }
    SSLExtension[] enabledExtensions =
        handshakeContext.sslConfig.getEnabledExtensions(
                SSLHandshake.CERTIFICATE_REQUEST);
    this.extensions = new SSLExtensions(this, m, enabledExtensions);
}
 
Example 2
@Override
public int write(String name, ByteBuffer src) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), false, true);

    int fd = file.openForAttributeAccess(followLinks);
    try {
        try {
            // open/create attribute file
            int afd = openat(fd, nameAsBytes(file,name),
                             (O_CREAT|O_WRONLY|O_TRUNC|O_XATTR),
                             UnixFileModeAttribute.ALL_PERMISSIONS);

            // wrap with channel
            FileChannel fc = UnixChannelFactory.newFileChannel(afd, file.toString(), false, true);

            // write value (nothing we can do if I/O error occurs)
            try {
                int rem = src.remaining();
                while (src.hasRemaining()) {
                    fc.write(src);
                }
                return rem;
            } finally {
                fc.close();
            }
        } catch (UnixException x) {
            throw new FileSystemException(file.getPathForExceptionMessage(),
                null, "Unable to write extended attribute '" + name +
                "': " + x.getMessage());
        }
    } finally {
        close(fd);
    }
}
 
Example 3
/**
 * Ideally, this is an instance method, but for now we're doing it here
 */
public static int serializedSizeOfBag(Bag bag) {
    if (bag != null) {
        BaggageWriter writer = BaggageWriter.create();
        bag.handler().serialize(writer, bag);
        int size = 0;
        for (ByteBuffer atom : writer.atoms()) {
            size += 1 + atom.remaining();
        }
        return size;
    }
    return 0;
}
 
Example 4
Source Project: r2cloud   File: Util.java    License: Apache License 2.0 5 votes vote down vote up
public static void readFully(ReadableByteChannel channel, ByteBuffer b) throws IOException {
	final int expectedLength = b.remaining();
	int read = 0;
	while (read < expectedLength) {
		int readNow = channel.read(b);
		if (readNow <= 0) {
			break;
		}
		read += readNow;
	}
	if (read < expectedLength) {
		throw new EOFException();
	}
}
 
Example 5
@Override
public void append(Framedata nextframe) {
    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 6
Source Project: diozero   File: PigpioJI2CDevice.java    License: MIT License 5 votes vote down vote up
@Override
public void write(ByteBuffer src) throws RuntimeIOException {
	if (! isOpen()) {
		throw new IllegalStateException("I2C Device " + controller + "-" + address + " is closed");
	}
	
	int to_write = src.remaining();
	byte[] buffer = new byte[to_write];
	src.get(buffer, src.position(), to_write);
	int rc = pigpioImpl.i2cWriteDevice(handle, buffer, to_write);
	if (rc < 0) {
		throw new RuntimeIOException("Error calling pigpioImpl.i2cWriteI2CBlockData(), response: " + rc);
	}
}
 
Example 7
Source Project: Tomcat8-Source-Read   File: Stream.java    License: MIT License 5 votes vote down vote up
@Override
public synchronized boolean writeFromBuffer(ByteBuffer src, boolean blocking) throws IOException {
    int chunkLimit = src.limit();
    while (src.remaining() > 0) {
        int thisTime = Math.min(buffer.remaining(), src.remaining());
        src.limit(src.position() + thisTime);
        buffer.put(src);
        src.limit(chunkLimit);
        if (flush(false, blocking)) {
            return true;
        }
    }
    return false;
}
 
Example 8
Source Project: grpc-java   File: ReadableBuffers.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public void readBytes(ByteBuffer dest) {
  Preconditions.checkNotNull(dest, "dest");
  int length = dest.remaining();
  checkReadable(length);

  // Change the limit so that only length bytes are available.
  int prevLimit = bytes.limit();
  bytes.limit(bytes.position() + length);

  // Write the bytes and restore the original limit.
  dest.put((ByteBuffer) bytes);
  bytes.limit(prevLimit);
}
 
Example 9
private int bytesInCompletePacket(ByteBuffer packet) throws SSLException {

        // DTLS length field is in bytes 11/12
        if (packet.remaining() < headerSize) {
            return -1;
        }

        // Last sanity check that it's not a wild record
        int pos = packet.position();

        // Check the content type of the record.
        byte contentType = packet.get(pos);
        if (ContentType.valueOf(contentType) == null) {
            throw new SSLException(
                    "Unrecognized SSL message, plaintext connection?");
        }

        // Check the protocol version of the record.
        byte majorVersion = packet.get(pos + 1);
        byte minorVersion = packet.get(pos + 2);
        if (!ProtocolVersion.isNegotiable(
                majorVersion, minorVersion, true, false)) {
            throw new SSLException("Unrecognized record version " +
                    ProtocolVersion.nameOf(majorVersion, minorVersion) +
                    " , plaintext connection?");
        }

        // Get the fragment length of the record.
        int fragLen = ((packet.get(pos + 11) & 0xFF) << 8) +
                       (packet.get(pos + 12) & 0xFF) + headerSize;
        if (fragLen > Record.maxFragmentSize) {
            throw new SSLException(
                    "Record overflow, fragment length (" + fragLen +
                    ") MUST not exceed " + Record.maxFragmentSize);
        }

        return fragLen;
    }
 
Example 10
private Beacon(ByteBuffer bytes) throws InvalidPacketException {
	super(bytes);
	if(bytes.remaining() != 6){
		throw new InvalidPacketException();
	}
	this.networkId = ((int)bytes.getShort()) & 0xffff;
	this.baseNonce = ((long)bytes.getInt()) & 0xffffffff;
}
 
Example 11
Source Project: tajo   File: Bytes.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * @param a left operand
 * @param buf right operand
 * @return True if equal
 */
public static boolean equals(byte[] a, ByteBuffer buf) {
  if (a == null) return buf == null;
  if (buf == null) return false;
  if (a.length != buf.remaining()) return false;

  // Thou shalt not modify the original byte buffer in what should be read only operations.
  ByteBuffer b = buf.duplicate();
  for (byte anA : a) {
    if (anA != b.get()) {
      return false;
    }
  }
  return true;
}
 
Example 12
@Override
public int read(String name, ByteBuffer dst) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), true, false);

    int fd = file.openForAttributeAccess(followLinks);
    try {
        try {
            // open attribute file
            int afd = openat(fd, nameAsBytes(file,name), (O_RDONLY|O_XATTR), 0);

            // wrap with channel
            FileChannel fc = UnixChannelFactory.newFileChannel(afd, file.toString(), true, false);

            // read to EOF (nothing we can do if I/O error occurs)
            try {
                if (fc.size() > dst.remaining())
                    throw new IOException("Extended attribute file too large");
                int total = 0;
                while (dst.hasRemaining()) {
                    int n = fc.read(dst);
                    if (n < 0)
                        break;
                    total += n;
                }
                return total;
            } finally {
                fc.close();
            }
        } catch (UnixException x) {
            throw new FileSystemException(file.getPathForExceptionMessage(),
                null, "Unable to read extended attribute '" + name +
                "': " + x.getMessage());
        }
    } finally {
        close(fd);
    }
}
 
Example 13
private void readHeaders(ByteBuffer buffer, StompHeaderAccessor headerAccessor) {
	while (true) {
		ByteArrayOutputStream headerStream = new ByteArrayOutputStream(256);
		boolean headerComplete = false;
		while (buffer.hasRemaining()) {
			if (tryConsumeEndOfLine(buffer)) {
				headerComplete = true;
				break;
			}
			headerStream.write(buffer.get());
		}
		if (headerStream.size() > 0 && headerComplete) {
			String header = new String(headerStream.toByteArray(), UTF8_CHARSET);
			int colonIndex = header.indexOf(':');
			if (colonIndex <= 0) {
				if (buffer.remaining() > 0) {
					throw new StompConversionException("Illegal header: '" + header +
							"'. A header must be of the form <name>:[<value>].");
				}
			}
			else {
				String headerName = unescape(header.substring(0, colonIndex));
				String headerValue = unescape(header.substring(colonIndex + 1));
				try {
					headerAccessor.addNativeHeader(headerName, headerValue);
				}
				catch (InvalidMimeTypeException ex) {
					if (buffer.remaining() > 0) {
						throw ex;
					}
				}
			}
		}
		else {
			break;
		}
	}
}
 
Example 14
Source Project: JavaSteam   File: WebSocketCMClient.java    License: MIT License 5 votes vote down vote up
@Override
public void onMessage(ByteBuffer bytes) {
    if (listener != null) {
        byte[] data = new byte[bytes.remaining()];
        bytes.get(data);
        listener.onData(data);
    }
}
 
Example 15
Source Project: Bytecoder   File: SSLCipher.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public int encrypt(byte contentType,
        ByteBuffer bb) {
    byte[] sn = authenticator.sequenceNumber();
    byte[] nonce = new byte[iv.length];
    System.arraycopy(sn, 0, nonce, nonce.length - sn.length,
            sn.length);
    for (int i = 0; i < nonce.length; i++) {
        nonce[i] ^= iv[i];
    }

    // initialize the AEAD cipher for the unique IV
    AlgorithmParameterSpec spec = new IvParameterSpec(nonce);
    try {
        cipher.init(Cipher.ENCRYPT_MODE, key, spec, random);
    } catch (InvalidKeyException |
                InvalidAlgorithmParameterException ikae) {
        // unlikely to happen
        throw new RuntimeException(
                    "invalid key or spec in AEAD mode", ikae);
    }

    // Update the additional authentication data, using the
    // implicit sequence number of the authenticator.
    int outputSize = cipher.getOutputSize(bb.remaining());
    byte[] aad = authenticator.acquireAuthenticationBytes(
                            contentType, outputSize, sn);
    cipher.updateAAD(aad);

    int len = bb.remaining();
    int pos = bb.position();
    if (SSLLogger.isOn && SSLLogger.isOn("plaintext")) {
        SSLLogger.fine(
                "Plaintext before ENCRYPTION",
                bb.duplicate());
    }

    ByteBuffer dup = bb.duplicate();
    if (outputSize > bb.remaining()) {
        // Need to expand the limit of the output buffer for
        // the authentication tag.
        //
        // DON'T worry about the buffer's capacity, we have
        // reserved space for the authentication tag.
        bb.limit(pos + outputSize);
    }

    try {
        len = cipher.doFinal(dup, bb);
    } catch (IllegalBlockSizeException |
                BadPaddingException | ShortBufferException ibse) {
        // unlikely to happen
        throw new RuntimeException(
                "Cipher error in AEAD mode in JCE provider " +
                cipher.getProvider().getName(), ibse);
    }

    if (len != outputSize) {
        throw new RuntimeException(
                "Cipher buffering error in JCE provider " +
                cipher.getProvider().getName());
    }

    if (keyLimitEnabled) {
        keyLimitCountdown -= len;
    }
    return len;
}
 
Example 16
public static Integer to_fixed32(ByteBuffer buf) {
    return buf.remaining() == 4 ? buf.getInt(buf.position()) : null;
}
 
Example 17
protected CoderResult decodeBufferLoop(ByteBuffer src, CharBuffer dst) {
    int mark = src.position();
    try {
        while (src.hasRemaining()) {
            char[] cc = null;
            int b1 = src.get() & 0xff;
            int inSize = 1, outSize = 1;
            char c = decodeSingle(b1);
            if (c == UNMAPPABLE_DECODING) {
                if (src.remaining() < 1)
                    return CoderResult.UNDERFLOW;
                int b2 = src.get() & 0xff;
                inSize++;
                if (b2 < b2Min || b2 > b2Max)
                    return CoderResult.unmappableForLength(2);
                c = decodeDouble(b1, b2);           //bmp
                if (c == UNMAPPABLE_DECODING) {
                    c = decodeDoubleEx(b1, b2);     //supp
                    if (c == UNMAPPABLE_DECODING) {
                        c = decodeBig5(b1, b2);     //big5
                        if (c == UNMAPPABLE_DECODING)
                            return CoderResult.unmappableForLength(2);
                    } else {
                        outSize = 2;
                    }
                }
            }
            if (dst.remaining() < outSize)
                return CoderResult.OVERFLOW;
            if (outSize == 2) {
                dst.put(Surrogate.high(0x20000 + c));
                dst.put(Surrogate.low(0x20000 + c));
            } else {
                dst.put(c);
            }
            mark += inSize;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(mark);
    }
}
 
Example 18
Source Project: RDFS   File: DataChecksum.java    License: Apache License 2.0 4 votes vote down vote up
/**
 * 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 (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;
  }
  
  int startDataPos = data.position();
  data.mark();
  checksums.mark();
  try {
    byte[] buf = new byte[bytesPerChecksum];
    byte[] sum = new byte[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
/**
* Convenience method returns the byte[] for the given index in the leaf. If
* the tuple at that index is a raw record, then the record is read from the
* backing store. More efficient operations should be performed when copying
* the value into a tuple.
* 
* @param leaf
*            The leaf.
* @param index
*            The index in the leaf.
* 
* @return The data.
* 
* @see AbstractTuple#copy(int, ILeafData)
*/
  public byte[] getValue(final int index) {
  	
if (!hasRawRecords()) {

	return getValues().get(index);
	
}

final long addr = getRawRecord(index);

if( addr == IRawStore.NULL) {

	return getValues().get(index);

}

final ByteBuffer tmp = htree.readRawRecord(addr);

if (tmp.hasArray() && tmp.arrayOffset() == 0 && tmp.position() == 0
		&& tmp.limit() == tmp.capacity()) {
	/*
	 * Return the backing array.
	 */
	return tmp.array();
}

/*
 * Copy the data into a byte[].
 */

final int len = tmp.remaining();

final byte[] a = new byte[len];

tmp.get(a);

return a;

  }
 
Example 20
Source Project: j2objc   File: BitSet.java    License: Apache License 2.0 3 votes vote down vote up
/**
 * Returns a new bit set containing all the bits in the given byte
 * buffer between its position and limit.
 *
 * <p>More precisely,
 * <br>{@code BitSet.valueOf(bb).get(n) == ((bb.get(bb.position()+n/8) & (1<<(n%8))) != 0)}
 * <br>for all {@code n < 8 * bb.remaining()}.
 *
 * <p>The byte buffer is not modified by this method, and no
 * reference to the buffer is retained by the bit set.
 *
 * @param bb a byte buffer containing a little-endian representation
 *        of a sequence of bits between its position and limit, to be
 *        used as the initial bits of the new bit set
 * @return a {@code BitSet} containing all the bits in the buffer in the
 *         specified range
 * @since 1.7
 */
public static BitSet valueOf(ByteBuffer bb) {
    bb = bb.slice().order(ByteOrder.LITTLE_ENDIAN);
    int n;
    for (n = bb.remaining(); n > 0 && bb.get(n - 1) == 0; n--)
        ;
    long[] words = new long[(n + 7) / 8];
    bb.limit(n);
    int i = 0;
    while (bb.remaining() >= 8)
        words[i++] = bb.getLong();
    for (int remaining = bb.remaining(), j = 0; j < remaining; j++)
        words[i] |= (bb.get() & 0xffL) << (8 * j);
    return new BitSet(words);
}