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:de.unibayreuth.bayeos.goat.table.MassenTableModel.java

public boolean load(ObjektNode objekt, TimeFilter tFilter, StatusFilter sFilter) {
    try {/*from   w  w  w .ja  v  a2s .  co m*/

        Vector params = new Vector();
        params.add(objekt.getId());
        params.add(tFilter.getVector());
        params.add(sFilter.getVector());
        Vector vReturn = (Vector) xmlClient.execute("MassenTableHandler.getRows", params);
        // Rows als byte[]
        byte[] ba = (byte[]) vReturn.elementAt(1);

        statusList = new ArrayByteList(ba.length / rowLength);
        vonList = new ArrayIntList(ba.length / rowLength);
        wertList = new ArrayDoubleList(ba.length / rowLength);

        ByteBuffer b = ByteBuffer.wrap(ba);
        while (b.hasRemaining()) {
            vonList.add(b.getInt());
            wertList.add((double) b.getFloat());
            statusList.add(b.get());
        }
        vReturn = null;
        logger.debug("MassenTableModel filled with " + getRowCount() + " records.");
        return true;
    } catch (XmlRpcException e) {
        MsgBox.error(e.getMessage());
        return false;
    }
}

From source file:record.wave.WaveWriter.java

/**
 * Opens the file and writes a wave header.
 *//* w  w w. ja va 2  s.  c om*/
private void open() throws IOException {
    int version = 2;

    while (Files.exists(mFile)) {
        mFile = Paths.get(mFile.toFile().getAbsolutePath().replace(".wav", "_" + version + ".wav"));
        version++;
    }

    mFileChannel = (FileChannel.open(mFile, StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW));

    ByteBuffer header = WaveUtils.getWaveHeader(mAudioFormat);

    header.flip();

    while (header.hasRemaining()) {
        mFileChannel.write(header);
    }
}

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

private static Map<UUID, List<UUID>> parseGraph(ByteBuffer graphByteBuffer, boolean bulkOnly) {
    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  w ww . jav a  2 s. c  om

    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) {
            UUID ref = uuids.get(refid);
            if (!bulkOnly || !isDataSegmentId(ref.getLeastSignificantBits())) {
                list.add(ref);
            }
            refid = buffer.getInt();
        }
        graph.put(uuid, list);
    }
    return graph;
}

From source file:com.streamsets.pipeline.lib.generator.wholefile.WholeFileDataGenerator.java

@Override
public void write(Record record) throws IOException, DataGeneratorException {
    validateRecord(record);/*from  w w  w  .ja va  2s  .  c om*/
    FileRef fileRef = record.get(FileRefUtil.FILE_REF_FIELD_PATH).getValueAsFileRef();
    int bufferSize = fileRef.getBufferSize();
    boolean canUseDirectByteBuffer = fileRef.getSupportedStreamClasses().contains(ReadableByteChannel.class);
    if (canUseDirectByteBuffer) {
        //Don't have to close this here, because generate.close will call output stream close
        WritableByteChannel writableByteChannel = Channels.newChannel(outputStream); //NOSONAR
        try (ReadableByteChannel readableByteChannel = getReadableStream(fileRef, ReadableByteChannel.class)) {
            ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
            while ((readableByteChannel.read(buffer)) > 0) {
                //Flip to use the buffer from 0 to position.
                buffer.flip();
                while (buffer.hasRemaining()) {
                    writableByteChannel.write(buffer);
                }
                //Compact the buffer for reuse.
                buffer.clear();
            }
        }
    } else {
        byte[] b = new byte[bufferSize];
        try (InputStream stream = getReadableStream(fileRef, InputStream.class)) {
            IOUtils.copyLarge(stream, outputStream, b);
        }
    }
}

From source file:com.offbynull.portmapper.pcp.PcpResponse.java

/**
 * MUST be called by child class constructor so that PCP options can be parsed.
 * @param buffer buffer containing PCP response data, with the pointer at the point which PCP options begin
 * @throws NullPointerException if any argument is {@code null}
 * @throws BufferUnderflowException if not enough data is available in {@code buffer}
 *///from  w w  w . j av  a 2  s .c o  m
protected final void parseOptions(ByteBuffer buffer) {
    Validate.notNull(buffer);

    List<PcpOption> pcpOptionsList = new ArrayList<>();
    while (buffer.hasRemaining()) {
        PcpOption option;

        try {
            buffer.mark();
            option = new FilterPcpOption(buffer);
            pcpOptionsList.add(option);
            continue;
        } catch (BufferUnderflowException | IllegalArgumentException e) {
            buffer.reset();
        }

        try {
            buffer.mark();
            option = new PreferFailurePcpOption(buffer);
            pcpOptionsList.add(option);
            continue;
        } catch (BufferUnderflowException | IllegalArgumentException e) {
            buffer.reset();
        }

        try {
            buffer.mark();
            option = new ThirdPartyPcpOption(buffer);
            pcpOptionsList.add(option);
            continue;
        } catch (BufferUnderflowException | IllegalArgumentException e) {
            buffer.reset();
        }

        option = new UnknownPcpOption(buffer);
        pcpOptionsList.add(option);
    }

    options = Collections.unmodifiableList(pcpOptionsList);
}

From source file:edu.umn.cs.spatialHadoop.core.ZCurvePartitioner.java

@Override
public void write(DataOutput out) throws IOException {
    mbr.write(out);/*from www. j  a v  a  2s .  c om*/
    out.writeInt(zSplits.length);
    ByteBuffer bbuffer = ByteBuffer.allocate(zSplits.length * 8);
    for (long zSplit : zSplits)
        bbuffer.putLong(zSplit);
    if (bbuffer.hasRemaining())
        throw new RuntimeException("Did not calculate buffer size correctly");
    out.write(bbuffer.array(), bbuffer.arrayOffset(), bbuffer.position());
}

From source file:com.saasovation.common.port.adapter.messaging.slothmq.SlothWorker.java

protected String receive() {
    SocketChannel socketChannel = null;

    try {//  w w  w .j a va  2 s  . c  om
        socketChannel = this.socket.accept();

        if (socketChannel == null) {
            return null; // if non-blocking
        }

        ReadableByteChannel readByteChannel = Channels.newChannel(socketChannel.socket().getInputStream());

        ByteArrayOutputStream byteArray = new ByteArrayOutputStream();

        ByteBuffer readBuffer = ByteBuffer.allocate(8);

        while (readByteChannel.read(readBuffer) != -1) {
            readBuffer.flip();

            while (readBuffer.hasRemaining()) {
                byteArray.write(readBuffer.get());
            }

            readBuffer.clear();
        }

        return new String(byteArray.toByteArray());

    } catch (IOException e) {
        logger.error("Failed to receive because: {}: Continuing...", e.getMessage(), e);
        return null;

    } finally {
        if (socketChannel != null) {
            try {
                socketChannel.close();
            } catch (IOException e) {
                // ignore
            }
        }
    }
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private void copyChannel(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

    while (src.read(buffer) != -1) {
        buffer.flip();// ww  w  . ja v  a  2s.  c  o  m
        dest.write(buffer);
        buffer.compact();
    }

    buffer.flip();

    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:org.thelq.stackexchange.api.StackClient.java

protected URI createUri(@NonNull BaseQuery<?, ?> query) {
    //Run query verification
    Map<String, String> finalParameters = query.buildFinalParameters();
    if (query.isAuthRequired() && StringUtils.isBlank(accessToken))
        throw new RuntimeException("Query " + query.getClass().getName() + " requires an accessToken");
    String method = query.getMethod().getFinal();
    if (method.contains("{}"))
        throw new RuntimeException("Unreplaced vector remaining in method " + method);

    //Build a URI manually
    StringBuilder uriBuilder = new StringBuilder("https://api.stackexchange.com/2.1/").append(method)
            .append("?");
    if (StringUtils.isNotBlank(seApiKey))
        uriBuilder.append("key=").append(seApiKey).append("&");
    for (Map.Entry<String, String> curParam : finalParameters.entrySet()) {
        if (curParam.getKey() == null || curParam.getValue() == null)
            throw new NullPointerException(
                    "Parameters cannot be null: " + curParam.getKey() + "=" + curParam.getValue());
        uriBuilder.append(curParam.getKey()).append("=");

        //Encode value
        final ByteBuffer bb = Charsets.UTF_8.encode(curParam.getValue());
        while (bb.hasRemaining()) {
            final int b = bb.get() & 0xff;
            if (URI_SAFECHARS.get(b))
                uriBuilder.append((char) b);
            else if (b == ' ')
                uriBuilder.append('+');
            else {
                uriBuilder.append("%");
                final char hex1 = Character.toUpperCase(Character.forDigit((b >> 4) & 0xF, 16));
                final char hex2 = Character.toUpperCase(Character.forDigit(b & 0xF, 16));
                uriBuilder.append(hex1);
                uriBuilder.append(hex2);
            }/*from   w w  w .j a v a 2 s .  c  o  m*/
        }
        uriBuilder.append("&");
    }
    char lastChar = uriBuilder.charAt(uriBuilder.length() - 1);
    if (lastChar == '&' || lastChar == '?')
        uriBuilder.deleteCharAt(uriBuilder.length() - 1);

    return URI.create(uriBuilder.toString());
}

From source file:edu.umn.cs.spatialHadoop.core.ZCurvePartitioner.java

@Override
public void readFields(DataInput in) throws IOException {
    mbr.readFields(in);/*  w  ww  .j  a  va 2  s.co  m*/
    int partitionCount = in.readInt();
    zSplits = new long[partitionCount];
    int bufferLength = 8 * partitionCount;
    byte[] buffer = new byte[bufferLength];
    in.readFully(buffer);
    ByteBuffer bbuffer = ByteBuffer.wrap(buffer);
    for (int i = 0; i < partitionCount; i++) {
        zSplits[i] = bbuffer.getLong();
    }
    if (bbuffer.hasRemaining())
        throw new RuntimeException("Error reading STR partitioner");
}