Example usage for java.nio ByteBuffer hasRemaining

List of usage examples for java.nio ByteBuffer hasRemaining

Introduction

In this page you can find the example usage for java.nio ByteBuffer hasRemaining.

Prototype

public final boolean hasRemaining() 

Source Link

Document

Indicates if there are elements remaining in this buffer, that is if position < limit .

Usage

From source file:ru.jts_dev.gameserver.movement.geoengine.GeoService.java

public void loadRegion(int x, int y, ByteBuffer byteBuffer) {
    Region region = new Region();
    int index = 0;

    byteBuffer.position(18);/*from w  w w  .j  a v a 2s. c  o m*/
    while (byteBuffer.hasRemaining()) {
        short type = byteBuffer.getShort();

        if (type == 0x0000) {
            // 1x short, flat block
            short maxHeight = (short) (byteBuffer.getShort() & 0x0fff0);
            short minHeight = (short) (byteBuffer.getShort() & 0x0fff0);

            Block block = new FlatBlock(minHeight, maxHeight);
            region.addBlock(x, y, index, block);
        } else if (type == 0x0040) { //type id from rebellion
            // 64x short, complex block
            Cell[] cells = new Cell[64];
            for (int cell = 0; cell < 64; cell++) {
                int value = byteBuffer.getShort();

                short height = (short) ((short) (value & 0x0fff0) >> 1);
                byte direction = (byte) (value & 0x0F);
                cells[cell] = new Cell(direction, height);
            }

            Block block = new ComplexBlock(cells);
            region.addBlock(x, y, index, block);
        } else { //0x0048 block id
            // 64x-8192x short, multilevel block
            short[][] height = new short[64][];
            byte[][] NSWE = new byte[64][];
            byte[] layersa = new byte[64];
            for (int cell = 0; cell < 64; cell++) {
                short layers = byteBuffer.getShort();

                height[cell] = new short[layers];
                NSWE[cell] = new byte[layers];
                for (int i = 0; i < layers; i++) {
                    int value = byteBuffer.getShort();
                    height[cell][i] = (short) ((short) (value & 0x0fff0) >> 1);
                    NSWE[cell][i] = (byte) (value & 0x0F);
                }
                layersa[cell] = (byte) --layers;
            }

            Block block = new MultilevelBlock(layersa, height, NSWE);
            region.addBlock(x, y, index, block);
        }

        index++;
    }
}

From source file:org.apache.jackrabbit.oak.plugins.segment.file.TarReader.java

private static Map<UUID, List<UUID>> parseGraph(ByteBuffer graphByteBuffer) {
    int count = graphByteBuffer.getInt(graphByteBuffer.limit() - 12);

    ByteBuffer buffer = graphByteBuffer.duplicate();
    buffer.limit(graphByteBuffer.limit() - 16);

    List<UUID> uuids = newArrayListWithCapacity(count);
    for (int i = 0; i < count; i++) {
        uuids.add(new UUID(buffer.getLong(), buffer.getLong()));
    }//from ww  w. j  a  va 2s.co  m

    Map<UUID, List<UUID>> graph = newHashMap();
    while (buffer.hasRemaining()) {
        UUID uuid = uuids.get(buffer.getInt());
        List<UUID> list = newArrayList();
        int refid = buffer.getInt();
        while (refid != -1) {
            list.add(uuids.get(refid));
            refid = buffer.getInt();
        }
        graph.put(uuid, list);
    }
    return graph;
}

From source file:internal.diff.aws.service.AmazonS3ETagFileChecksumServiceImpl.java

@Override
public String calculateChecksum(Path file) throws IOException {

    long fileSize = Files.size(file);

    int parts = (int) (fileSize / S3_MULTIPART_SIZE_LIMIT_IN_BYTES);
    parts += fileSize % S3_MULTIPART_SIZE_LIMIT_IN_BYTES > 0 ? 1 : 0;

    ByteBuffer checksumBuffer = ByteBuffer.allocate(parts * 16);

    SeekableByteChannel byteChannel = Files.newByteChannel(file);

    for (int part = 0; part < parts; part++) {

        int partSizeInBytes;

        if (part < parts - 1 || fileSize % S3_MULTIPART_SIZE_LIMIT_IN_BYTES == 0) {
            partSizeInBytes = S3_MULTIPART_SIZE_LIMIT_IN_BYTES;
        } else {//ww  w.java  2s . com
            partSizeInBytes = (int) (fileSize % S3_MULTIPART_SIZE_LIMIT_IN_BYTES);
        }

        ByteBuffer partBuffer = ByteBuffer.allocate(partSizeInBytes);

        boolean endOfFile;
        do {
            endOfFile = byteChannel.read(partBuffer) == -1;
        } while (!endOfFile && partBuffer.hasRemaining());

        checksumBuffer.put(DigestUtils.md5(partBuffer.array()));
    }

    if (parts > 1) {
        return DigestUtils.md5Hex(checksumBuffer.array()) + "-" + parts;
    } else {
        return Hex.encodeHexString(checksumBuffer.array());
    }
}

From source file:org.lnicholls.galleon.util.Tools.java

public static InputStream getInputStream(File file) {
    try {//from   w w  w. j  a  va 2 s. c o m
        FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
        final ByteBuffer buf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel.size());
        return new InputStream() {
            public synchronized int read() throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                return buf.get();
            }

            public synchronized int read(byte[] bytes, int off, int len) throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                len = Math.min(len, buf.remaining());
                buf.get(bytes, off, len);
                return len;
            }
        };
    } catch (Exception ex) {
        Tools.logException(Tools.class, ex, file.getAbsolutePath());
    }
    return null;
}

From source file:one.xmpp.xml.XmlTokenizer.java

/**
 * @param byteBuffer//  w ww  .j  av a2s  .c om
 * @param charsetDecoder
 * @return the new particle or NULL, if the buffer was exhausted before the particle was
 *         completed
 * @throws Exception
 */
public void parse(ByteBuffer byteBuffer) throws BadFormatError {
    while (byteBuffer.hasRemaining() && state != State.CLOSED) {
        final byte b = byteBuffer.get();
        final char c = (char) b;

        try {

            if (state == State.START) {
                if (c == '<') {
                    emit(c);
                    state = State.IN_TAG;
                } else {
                    state = State.IN_TEXT;
                    buffer.put((byte) c);
                }
            } else if (state == State.IN_TEXT) {
                if (c == '<') {
                    emitBuffer();
                    emit(c);
                    state = State.IN_TAG;
                } else {
                    buffer.put(b);
                }
            } else if (state == State.IN_TAG) {
                if (c == '>') {
                    emit(c);
                    state = State.START;
                } else if (c == '"') {
                    emit(c);
                    state = State.IN_DOUBLE_ATTRIBUTE_VALUE;
                } else if (c == '\'') {
                    emit(c);
                    state = State.IN_SINGLE_ATTRIBUTE_VALUE;
                } else if (c == '-') {
                    emit(c);
                } else if (isControlChar(c)) {
                    emit(c);
                } else if (Character.isWhitespace(c)) {
                    buffer.clear();
                } else {
                    state = State.IN_STRING;
                    buffer.put(b);
                }
            } else if (state == State.IN_STRING) {
                if (c == '>') {
                    emitBuffer();
                    emit(c);
                    state = State.START;
                } else if (isControlChar(c)) {
                    emitBuffer();
                    emit(c);
                    state = State.IN_TAG;
                } else if (Character.isWhitespace(c)) {
                    emitBuffer();
                    state = State.IN_TAG;
                } else {
                    buffer.put(b);
                }
            } else if (state == State.IN_DOUBLE_ATTRIBUTE_VALUE) {
                if (c == '"') {
                    emitBuffer();
                    emit(c);
                    state = State.IN_TAG;
                } else {
                    buffer.put(b);
                }
            } else if (state == State.IN_SINGLE_ATTRIBUTE_VALUE) {
                if (c == '\'') {
                    emitBuffer();
                    emit(c);
                    state = State.IN_TAG;
                } else {
                    buffer.put(b);
                }
            }

        } catch (Exception exc) {
            throw new BadFormatError("Unable to parse XML, next byte is " + b + " ('"
                    + StringEscapeUtils.escapeJava("" + c) + "'); exc: " + exc, exc);
        }
    }
}

From source file:org.lnicholls.galleon.util.Tools.java

public static BufferedImage ImageIORead(File file) {
    System.gc();/*from w ww  .j  a va2 s.  co m*/
    try {
        FileChannel roChannel = new RandomAccessFile(file, "r").getChannel();
        final ByteBuffer buf = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int) roChannel.size());
        return ImageIO.read(new InputStream() {
            public synchronized int read() throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                return buf.get();
            }

            public synchronized int read(byte[] bytes, int off, int len) throws IOException {
                if (!buf.hasRemaining()) {
                    return -1;
                }
                len = Math.min(len, buf.remaining());
                buf.get(bytes, off, len);
                return len;
            }
        });
    } catch (Exception ex) {
        Tools.logException(Tools.class, ex, file.getAbsolutePath());
    }

    try {
        return ImageIO.read(new FileInputStream(file));
    } catch (Exception ex) {
        Tools.logException(Tools.class, ex, file.getAbsolutePath());
    }
    return null;
}

From source file:net.socket.nio.TimeClientHandle.java

private void doWrite(SocketChannel sc) throws IOException {
    byte[] req = "QUERY TIME ORDER".getBytes();
    ByteBuffer writeBuffer = ByteBuffer.allocate(req.length);
    writeBuffer.put(req);//from   w ww.  j a v  a  2s .c  om
    writeBuffer.flip();
    sc.write(writeBuffer);
    sc.write(writeBuffer);
    if (!writeBuffer.hasRemaining()) {
        System.out.println("Send order 2 server succeed.");
    }
}

From source file:org.commoncrawl.hadoop.mergeutils.MergeSortSpillWriter.java

public static InputStream newInputStream(final ByteBuffer buf) {
    return new InputStream() {
        public synchronized int read() throws IOException {
            if (!buf.hasRemaining()) {
                return -1;
            }// w  w w . j  a  v a2 s .c om
            return buf.get() & 0xff;
        }

        public synchronized int read(byte[] bytes, int off, int len) throws IOException {
            // Read only what's left
            len = Math.min(len, buf.remaining());
            buf.get(bytes, off, len);
            return len;
        }
    };
}

From source file:nl.salp.warcraft4j.casc.cdn.online.CachingOnlineDataReaderProvider.java

/**
 * Cache a file, overwriting the previous version if existing.
 *
 * @param url The URL of the file to cache.
 *
 * @return The path of the cached file.//from   w  w  w  .j av  a  2s  . co m
 *
 * @throws IOException When reading the file or writing the cached version of the file fails.
 */
private Path cache(String url) throws IOException {
    Path file = toCacheFile(url);
    LOGGER.trace("Caching CDN file {} to {}", url, file);
    if (!Files.exists(file.getParent())) {
        LOGGER.trace("Creating directory structure {} to cache file {}", file.getParent(), file);
        Files.createDirectories(file.getParent());
    }
    try (DataReader fileDataReader = new CachedHttpDataReader(url);
            ByteChannel cachedFileChannel = Files.newByteChannel(file, CREATE, WRITE, TRUNCATE_EXISTING)) {
        long fileSize = 0;
        while (fileDataReader.hasRemaining()) {
            int chunkSize = (int) Math.min(CACHE_CHUNK_SIZE, fileDataReader.remaining());
            ByteBuffer dataBuffer = ByteBuffer
                    .wrap(fileDataReader.readNext(DataTypeFactory.getByteArray(chunkSize)));
            while (dataBuffer.hasRemaining()) {
                fileSize += cachedFileChannel.write(dataBuffer);
            }
        }
        LOGGER.trace("Cached {} byte CDN file {} to {}", fileSize, url, file);
    }
    return file;
}

From source file:com.netflix.genie.web.services.impl.DiskJobFileServiceImpl.java

/**
 * {@inheritDoc}/*from  w  ww . j av  a2 s  .  c  o m*/
 */
@Override
// TODO: We should be careful about how large the byte[] is. Perhaps we should have precondition to protect memory
//       or we should wrap calls to this in something that chunks it off an input stream or just take this in as
//       input stream
public void updateFile(final String jobId, final String relativePath, final long startByte, final byte[] data)
        throws IOException {
    log.debug("Attempting to write {} bytes from position {} into log file {} for job {}", data.length,
            startByte, relativePath, jobId);
    final Path jobFile = this.jobsDirRoot.resolve(jobId).resolve(relativePath);

    if (Files.notExists(jobFile)) {
        // Make sure all the directories exist on disk
        final Path logFileParent = jobFile.getParent();
        if (logFileParent != null) {
            this.createOrCheckDirectory(logFileParent);
        }
    } else if (Files.isDirectory(jobFile)) {
        // TODO: Perhaps this should be different exception
        throw new IllegalArgumentException(relativePath + " is a directory not a file. Unable to update");
    }

    try (FileChannel fileChannel = FileChannel.open(jobFile,
            EnumSet.of(StandardOpenOption.CREATE, StandardOpenOption.WRITE, StandardOpenOption.SPARSE))) {
        // Move the byteChannel to the start byte
        fileChannel.position(startByte);

        // The size and length are ignored in this implementation as we just assume we're writing everything atm
        // TODO: Would it be better to provide an input stream and buffer the output?
        final ByteBuffer byteBuffer = ByteBuffer.wrap(data);

        while (byteBuffer.hasRemaining()) {
            fileChannel.write(byteBuffer);
        }
    }
}