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

The following are Jave code examples for showing how to use hasRemaining() 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: hadoop   File: SocketOutputStream.java   View Source Code Vote up 6 votes
@Override
public void write(byte[] b, int off, int len) throws IOException {
  ByteBuffer buf = ByteBuffer.wrap(b, off, len);
  while (buf.hasRemaining()) {
    try {
      if (write(buf) < 0) {
        throw new IOException("The stream is closed");
      }
    } catch (IOException e) {
      /* Unlike read, write can not inform user of partial writes.
       * So will close this if there was a partial write.
       */
      if (buf.capacity() > buf.remaining()) {
        writer.close();
      }
      throw e;
    }
  }
}
 
Example 2
Project: FApkSigner   File: ByteArrayDataSink.java   View Source Code Vote up 6 votes
@Override
public void consume(ByteBuffer buf) throws IOException {
    if (!buf.hasRemaining()) {
        return;
    }

    if (buf.hasArray()) {
        consume(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining());
        buf.position(buf.limit());
        return;
    }

    ensureAvailable(buf.remaining());
    byte[] tmp = new byte[Math.min(buf.remaining(), MAX_READ_CHUNK_SIZE)];
    while (buf.hasRemaining()) {
        int chunkSize = Math.min(buf.remaining(), tmp.length);
        buf.get(tmp, 0, chunkSize);
        System.arraycopy(tmp, 0, mArray, mSize, chunkSize);
        mSize += chunkSize;
    }
}
 
Example 3
Project: sstore-soft   File: ConstraintFailureException.java   View Source Code Vote up 6 votes
/**
 * Constructor for deserializing an exception returned from the EE.
 * @param exceptionBuffer
 */
public ConstraintFailureException(ByteBuffer exceptionBuffer) {
    super(exceptionBuffer);
    type = ConstraintType.get(exceptionBuffer.getInt());
    try {
        tableName = FastDeserializer.readString(exceptionBuffer);
    }
    catch (IOException e) {
        // implies that the EE created an invalid constraint
        // failure, which would be a corruption/defect.
        throw new ServerFaultException("Unexpected error when deserializing exception from EE", e);
    }
    if (exceptionBuffer.hasRemaining()) {
        int tableSize = exceptionBuffer.getInt();
        buffer = ByteBuffer.allocate(tableSize);
        //Copy the exception details.
        exceptionBuffer.get(buffer.array());
    } else {
        buffer = ByteBuffer.allocate(0);
    }
}
 
Example 4
Project: otus_java_2017_06   File: NioMain.java   View Source Code Vote up 6 votes
public static void main(String[] args) throws Exception {
    try (RandomAccessFile aFile = new RandomAccessFile("data/data.txt", "rw")) {
        FileChannel inChannel = aFile.getChannel();

        ByteBuffer buf = ByteBuffer.allocate(1024);

        int bytesRead = inChannel.read(buf);
        while (bytesRead != -1) {

            System.out.println("Read " + bytesRead);
            buf.flip();

            while (buf.hasRemaining()) {
                System.out.print((char) buf.get());
            }
            System.out.print("\n");
            buf.clear();
            bytesRead = inChannel.read(buf);
        }
    }
}
 
Example 5
Project: mycat-src-1.6.1-RELEASE   File: BufferPerformanceMain.java   View Source Code Vote up 6 votes
public void copyArray() {
    ByteBuffer buffer = ByteBuffer.allocate(4096);
    while (buffer.hasRemaining()) {
        buffer.put((byte) 1);
    }
    byte[] b = new byte[1024];
    int count = 10000000;
    System.currentTimeMillis();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        buffer.position(0);
        buffer.get(b, 0, b.length);
    }
    long t2 = System.currentTimeMillis();
    System.out.println("take time:" + (t2 - t1) + " ms.(testCopyArray)");
}
 
Example 6
Project: openjdk-jdk10   File: SingleByteDecoder.java   View Source Code Vote up 6 votes
private CoderResult decodeBufferLoop(ByteBuffer src, CharBuffer dst) {
    int mark = src.position();
    try {
        while (src.hasRemaining()) {
            int b = src.get();

            char c = decode(b);
            if (c == '\uFFFD')
                return CoderResult.unmappableForLength(1);
            if (!dst.hasRemaining())
                return CoderResult.OVERFLOW;
            mark++;
            dst.put(c);
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(mark);
    }
}
 
Example 7
Project: openjdk-jdk10   File: SolarisUserDefinedFileAttributeView.java   View Source Code Vote up 5 votes
@Override
public int write(String name, ByteBuffer src) throws IOException {
    if (System.getSecurityManager() != null)
        checkAccess(file.getPathForPermissionCheck(), false, true);

    int fd = -1;
    try {
        try {
            fd = file.openForAttributeAccess(followLinks);

            // 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 8
Project: spur   File: Res.java   View Source Code Vote up 5 votes
public void send(Object obj) {
    if (httpServerExchange.getRequestMethod()
            .equals(HEAD)) {
        httpServerExchange.endExchange();
        return;
    }
    httpServerExchange.getResponseHeaders()
            .put(Headers.CONTENT_TYPE, JSON_CONTENT_TYPE);

    ObjectMapper objectMapper = LOCAL_MAPPER.get();
    if (objectMapper == null) {
        LOGGER.info("Creating new parser.........");
        objectMapper = JsonFactory.createUseJSONDates();
        LOCAL_MAPPER.set(objectMapper);
    }

    String jsonStr = objectMapper
            .toJson(obj);
    ByteBuffer byteBuffer = ByteBuffer.wrap(jsonStr.getBytes(StandardCharsets.UTF_8));
    StreamSinkChannel responseChannel = httpServerExchange.getResponseChannel();
    int written;
    try {
        do {
            written = responseChannel.write(byteBuffer);
        } while (byteBuffer.hasRemaining() && written > 0);
    } catch (IOException e) {
        LOGGER.error("Can not write response: " + e.getMessage(), e);
    }
}
 
Example 9
Project: guava-mock   File: Murmur3_32HashFunction.java   View Source Code Vote up 5 votes
@Override
protected void processRemaining(ByteBuffer bb) {
  length += bb.remaining();
  int k1 = 0;
  for (int i = 0; bb.hasRemaining(); i += 8) {
    k1 ^= toInt(bb.get()) << i;
  }
  h1 ^= Murmur3_32HashFunction.mixK1(k1);
}
 
Example 10
Project: lazycat   File: WsFrame.java   View Source Code Vote up 5 votes
private void blockingRead(UpgradeProcessor<?> processor, ByteBuffer bb) throws IOException {
	int last = 0;
	while (bb.hasRemaining()) {
		last = processor.read();
		if (last == -1) {
			throw new IOException(sm.getString("frame.eos"));
		}
		bb.put((byte) (last ^ mask[bb.position() % 4]));
	}
	bb.flip();
}
 
Example 11
Project: chromium-net-for-android   File: ChromiumUrlRequest.java   View Source Code Vote up 5 votes
/**
 * Consumes a portion of the response.
 *
 * @param byteBuffer The ByteBuffer to append. Must be a direct buffer, and
 *            no references to it may be retained after the method ends, as
 *            it wraps code managed on the native heap.
 */
@CalledByNative
private void onBytesRead(ByteBuffer buffer) {
    try {
        if (mContentLengthOverLimit) {
            return;
        }

        int size = buffer.remaining();
        mSize += size;
        if (mSkippingToOffset) {
            if (mSize <= mOffset) {
                return;
            } else {
                mSkippingToOffset = false;
                buffer.position((int) (mOffset - (mSize - size)));
            }
        }

        boolean contentLengthOverLimit =
                (mContentLengthLimit != 0 && mSize > mContentLengthLimit);
        if (contentLengthOverLimit) {
            buffer.limit(size - (int) (mSize - mContentLengthLimit));
        }

        while (buffer.hasRemaining()) {
            mSink.write(buffer);
        }
        if (contentLengthOverLimit) {
            onContentLengthOverLimit();
        }
    } catch (Exception e) {
        onCalledByNativeException(e);
    }
}
 
Example 12
Project: s3-channels   File: S3RangedReadObjectChannel.java   View Source Code Vote up 5 votes
@Override
public int read(ByteBuffer dst, long position) throws IOException {
    if (!dst.hasRemaining()) {
        return 0;
    }
    S3Object object = s3.getObject(new GetObjectRequest(bucket, key)
            .withRange(position, position + dst.remaining()));
    return ByteBufferUtils.readFromInputStream(object.getObjectContent(), dst, true);
}
 
Example 13
Project: distmq   File: Segment.java   View Source Code Vote up 5 votes
public boolean append(BrokerMessage.MessageContent.Builder messageBuilder) {
    try {
        if (fileSize == 0) {
            messageBuilder.setOffset(startOffset);
        } else {
            messageBuilder.setOffset(endOffset);
        }
        messageBuilder.setCreateTime(System.currentTimeMillis());
        BrokerMessage.MessageContent message = messageBuilder.build();
        byte[] messageBytes = message.toByteArray();
        int totalSize = Segment.MESSAGE_HEADER_LENGTH + messageBytes.length;
        ByteBuffer byteBuffer = ByteBuffer.allocate(totalSize);
        byteBuffer.putLong(BrokerUtils.getCRC32(messageBytes));
        byteBuffer.putInt(messageBytes.length);
        byteBuffer.put(messageBytes);
        byteBuffer.flip();
        channel.position(channel.size());
        int writeSize = 0;
        while (byteBuffer.hasRemaining()) {
            writeSize += channel.write(byteBuffer);
        }
        channel.force(true);
        if (writeSize != totalSize) {
            LOG.warn("append message failed");
            return false;
        }
        if (fileSize == 0) {
            endOffset = startOffset + writeSize;
        } else {
            endOffset += writeSize;
        }
        fileSize += writeSize;
    } catch (IOException ex) {
        LOG.warn("append message exception:", ex);
        return false;
    }
    return true;
}
 
Example 14
Project: openjdk-jdk10   File: DataProviders.java   View Source Code Vote up 5 votes
private static ByteBuffer fill(ByteBuffer b) {
    int i = 0;
    while (b.hasRemaining()) {
        b.put((byte) (++i & 0xff));
    }
    return b;
}
 
Example 15
Project: atlas   File: Dex.java   View Source Code Vote up 5 votes
public void writeTo(OutputStream out) throws IOException {
    byte[] buffer = new byte[8192];
    ByteBuffer data = this.data.duplicate(); // positioned ByteBuffers aren't thread safe
    data.clear();
    while (data.hasRemaining()) {
        int count = Math.min(buffer.length, data.remaining());
        data.get(buffer, 0, count);
        out.write(buffer, 0, count);
    }
}
 
Example 16
Project: dubbo2   File: ChannelBuffers.java   View Source Code Vote up 5 votes
public static ChannelBuffer wrappedBuffer(ByteBuffer buffer) {
    if (!buffer.hasRemaining()) {
        return EMPTY_BUFFER;
    }
    if (buffer.hasArray()) {
        return wrappedBuffer(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());
    } else {
        return new ByteBufferBackedChannelBuffer(buffer);
    }
}
 
Example 17
Project: openjdk-jdk10   File: DirectBBRemaining.java   View Source Code Vote up 4 votes
private static void encrypt(Cipher cipher, int size,
        ByteBuffer heapIn, ByteBuffer heapOut,
        ByteBuffer directIn, ByteBuffer directOut,
        boolean output) throws Exception {

    ByteBuffer inBB = null;
    ByteBuffer outBB = null;

    // Set up data and encrypt to known/expected values.
    byte[] testdata = new byte[size];
    random.nextBytes(testdata);
    byte[] expected = cipher.doFinal(testdata);

    for (TestVariant tv : TestVariant.values()) {
        if (output) {
            System.out.print(" " + tv);
        }

        switch (tv) {
        case HEAP_HEAP:
            inBB = heapIn;
            outBB = heapOut;
            break;
        case HEAP_DIRECT:
            inBB = heapIn;
            outBB = directOut;
            break;
        case DIRECT_HEAP:
            inBB = directIn;
            outBB = heapOut;
            break;
        case DIRECT_DIRECT:
            inBB = directIn;
            outBB = directOut;
            break;
        }

        inBB.clear();
        outBB.clear();

        inBB.put(testdata);
        inBB.flip();

        // Process all data in one shot, but don't call doFinal() yet.
        // May store up to n-1 bytes (w/block size n) internally.
        cipher.update(inBB, outBB);
        if (inBB.hasRemaining()) {
            throw new Exception("buffer not empty");
        }

        // finish encryption and process all data buffered
        cipher.doFinal(inBB, outBB);
        outBB.flip();

        // validate output size
        if (outBB.remaining() != expected.length) {
            throw new Exception(
                    "incomplete encryption output, expected "
                    + expected.length + " bytes but was only "
                    + outBB.remaining() + " bytes");
        }

        // validate output data
        byte[] encrypted = new byte[outBB.remaining()];
        outBB.get(encrypted);
        if (!Arrays.equals(expected, encrypted)) {
            throw new Exception("bad encryption output");
        }

        if (!Arrays.equals(cipher.doFinal(), cipher.doFinal())) {
            throw new Exception("Internal buffers still held data!");
        }
    }
}
 
Example 18
Project: lazycat   File: NioSelectorPool.java   View Source Code Vote up 4 votes
public int write(ByteBuffer buf, NioChannel socket, Selector selector, long writeTimeout, boolean block)
		throws IOException {
	if (SHARED && block) {
		return blockingSelector.write(buf, socket, writeTimeout);
	}
	SelectionKey key = null;
	int written = 0;
	boolean timedout = false;
	int keycount = 1; // assume we can write
	long time = System.currentTimeMillis(); // start the timeout timer
	try {
		while ((!timedout) && buf.hasRemaining()) {
			int cnt = 0;
			if (keycount > 0) { // only write if we were registered for a
								// write
				cnt = socket.write(buf); // write the data
				if (cnt == -1)
					throw new EOFException();

				written += cnt;
				if (cnt > 0) {
					time = System.currentTimeMillis(); // reset our timeout
														// timer
					continue; // we successfully wrote, try again without a
								// selector
				}
				if (cnt == 0 && (!block))
					break; // don't block
			}
			if (selector != null) {
				// register OP_WRITE to the selector
				if (key == null)
					key = socket.getIOChannel().register(selector, SelectionKey.OP_WRITE);
				else
					key.interestOps(SelectionKey.OP_WRITE);
				keycount = selector.select(writeTimeout);
			}
			if (writeTimeout > 0 && (selector == null || keycount == 0))
				timedout = (System.currentTimeMillis() - time) >= writeTimeout;
		} // while
		if (timedout)
			throw new SocketTimeoutException();
	} finally {
		if (key != null) {
			key.cancel();
			if (selector != null)
				selector.selectNow();// removes the key from this selector
		}
	}
	return written;
}
 
Example 19
Project: OpenJSharp   File: DoubleByte.java   View Source Code Vote up 4 votes
protected CoderResult decodeBufferLoop(ByteBuffer src, CharBuffer dst) {
    int mark = src.position();
    try {
        while (src.hasRemaining()) {
            int b1 = src.get() & 0xff;
            int inSize = 1;
            if (b1 == SO) {  // Shift out
                if (currentState != SBCS)
                    return CoderResult.malformedForLength(1);
                else
                    currentState = DBCS;
            } else if (b1 == SI) {
                if (currentState != DBCS)
                    return CoderResult.malformedForLength(1);
                else
                    currentState = SBCS;
            } else {
                char c = UNMAPPABLE_DECODING;
                if (currentState == SBCS) {
                    c = b2cSB[b1];
                    if (c == UNMAPPABLE_DECODING)
                        return CoderResult.unmappableForLength(1);
                } else {
                    if (src.remaining() < 1)
                        return CoderResult.UNDERFLOW;
                    int b2 = src.get()&0xff;
                    if (b2 < b2Min || b2 > b2Max ||
                        (c = b2c[b1][b2 - b2Min]) == UNMAPPABLE_DECODING) {
                        if (!isDoubleByte(b1, b2))
                            return CoderResult.malformedForLength(2);
                        return CoderResult.unmappableForLength(2);
                    }
                    inSize++;
                }

                if (dst.remaining() < 1)
                    return CoderResult.OVERFLOW;

                dst.put(c);
            }
            mark += inSize;
        }
        return CoderResult.UNDERFLOW;
    } finally {
        src.position(mark);
    }
}
 
Example 20
Project: lams   File: ChunkReader.java   View Source Code Vote up 4 votes
public int handle(ByteBuffer buf) throws IOException {
    while (buf.hasRemaining()) {
        final byte b = buf.get();
        if (state == STATE_TRAILER_NAME) {
            if (b == '\r') {
                if (builder.length() == 0) {
                    state = STATE_ENDING;
                } else {
                    throw UndertowMessages.MESSAGES.couldNotDecodeTrailers();
                }
            } else if (b == '\n') {
                if (builder.length() == 0) {
                    attachable.putAttachment(trailerAttachmentKey, headerMap);
                    return -1;
                } else {
                    throw UndertowMessages.MESSAGES.couldNotDecodeTrailers();
                }
            } else if (b == ':') {
                httpString = HttpString.tryFromString(builder.toString().trim());
                state = STATE_TRAILER_VALUE;
                builder.setLength(0);
            } else {
                builder.append((char) b);
            }
        } else if (state == STATE_TRAILER_VALUE) {
            if (b == '\n') {
                headerMap.put(httpString, builder.toString().trim());
                httpString = null;
                builder.setLength(0);
                state = STATE_TRAILER_NAME;
            } else if (b != '\r') {
                builder.append((char) b);
            }
        } else if (state == STATE_ENDING) {
            if (b == '\n') {
                if (attachable != null) {
                    attachable.putAttachment(trailerAttachmentKey, headerMap);
                }
                return -1;
            } else {
                throw UndertowMessages.MESSAGES.couldNotDecodeTrailers();
            }
        } else {
            throw new IllegalStateException();
        }
    }
    return 0;
}