Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(byte[] src, int off, int len) 

Source Link

Document

Writes bytes in the given byte array, starting from the specified offset, to the current position and increases the position by the number of bytes written.

Usage

From source file:Main.java

public static byte[] genSirfCommand(String commandHexa) {
    int length = commandHexa.length() / 2;
    ByteBuffer command = ByteBuffer.allocate(length);
    command.put(new BigInteger(commandHexa, 16).toByteArray(), 1, length);
    return command.array();
}

From source file:neembuu.uploader.external.HttpUtil.java

private static ReadableByteChannel wrap(final InputStream is, final HttpEntity he, final Content c,
        final double contentLength) {
    return new ReadableByteChannel() {
        double total = 0;

        @Override//from  ww  w  . ja  v  a  2 s .  c o  m
        public int read(ByteBuffer dst) throws IOException {
            byte[] b = new byte[dst.capacity()];
            int r = is.read(b);
            //this sleep is just to slow down update to see, if the UI is working or not !
            // NU's update is very very very fast
            //try{Thread.sleep(1000);}catch(Exception a){}
            dst.put(b, 0, r);
            total += r;
            c.setProgress(total / contentLength);
            return r;
        }

        @Override
        public boolean isOpen() {
            return he.isStreaming();
        }

        @Override
        public void close() throws IOException {
            is.close();
        }
    };
}

From source file:com.serotonin.bacnet4j.util.sero.StreamUtils.java

public static void transfer(InputStream in, SocketChannel out) throws IOException {
    byte[] buf = new byte[1024];
    ByteBuffer bbuf = ByteBuffer.allocate(1024);
    int len;/*from  w  w w  .  j  a  va  2s .co  m*/
    while ((len = in.read(buf)) != -1) {
        bbuf.put(buf, 0, len);
        bbuf.flip();
        while (bbuf.remaining() > 0)
            out.write(bbuf);
        bbuf.clear();
    }
}

From source file:com.fujitsu.dc.test.jersey.bar.BarInstallTestUtils.java

/**
 * bar?.//w ww  .ja  v a 2  s  . c o  m
 * @param barFile bar?
 * @return ??bar
 */
public static byte[] readBarFile(File barFile) {
    InputStream is = ClassLoader.getSystemResourceAsStream(barFile.getPath());
    ByteBuffer buff = ByteBuffer.allocate(READ_BUFFER_SIZE);
    log.debug(String.valueOf(buff.capacity()));
    try {
        byte[] bbuf = new byte[SIZE_KB];
        int size;
        while ((size = is.read(bbuf)) != -1) {
            buff.put(bbuf, 0, size);
        }
    } catch (IOException e) {
        throw new RuntimeException("failed to load bar file:" + barFile.getPath(), e);
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            throw new RuntimeException("failed to close bar file:" + barFile.getPath(), e);
        }
    }
    int size = buff.position();
    buff.flip();
    byte[] retv = new byte[size];
    buff.get(retv, 0, size);
    return retv;
}

From source file:com.glaf.core.util.ByteBufferUtils.java

/**
 *  byte[] buffer//from ww  w.j a v  a2  s.co  m
 * 
 * @param toBuffer
 * @param bytes
 * @param offset
 * @param len
 */
public static void append(ByteBuffer toBuffer, byte[] bytes, int offset, int len) { // ?
    int pos = flipToFill(toBuffer);
    try {
        toBuffer.put(bytes, offset, len);
    } finally {
        // ?
        flipToFlush(toBuffer, pos);
    }
}

From source file:net.anidb.udp.UdpResponse.java

/**
 * Returns a instance of the class.// w  w w .  jav a 2 s. c  o  m
 * @param packet The datagram packet.
 * @param charset The charset.
 * @return The instance.
 * @throws IllegalArgumentException If the datagram packet is
 * <code>null</code>.
 * @throws UdpConnectionException If the structure of datagram packet isn't
 * valid.
 * @throws UnsupportedEncodingException If the given charset isn't
 * supported.
 */
protected static UdpResponse getInstance(final DatagramPacket packet, final Charset charset)
        throws UdpConnectionException, UnsupportedEncodingException {

    ByteBuffer byteBuffer;
    String data, returnCodeStr, returnString;
    int returnCode;
    UdpResponse response;
    int index;
    String[] entries, dataFields;
    UdpResponseEntry entry;

    if (packet == null) {
        throw new IllegalArgumentException("Argument packet is null.");
    }
    if (packet.getLength() < 5) {
        throw new UdpConnectionException(
                "The packet length is less than " + "the minimum of 5 bytes: " + packet.getLength());
    }
    byteBuffer = ByteBuffer.allocate(packet.getLength());
    byteBuffer = (ByteBuffer) byteBuffer.put(packet.getData(), 0, packet.getLength()).flip();
    data = charset.decode(byteBuffer).toString();
    LOG.debug("received = [" + data + ']');
    if (data.length() < 5) {
        throw new UdpConnectionException(
                "The string length is less than " + "the minimum of 5 characters: " + data);
    }
    // First 3 chars = return code
    returnCodeStr = data.substring(0, 3);
    data = data.substring(4);
    try {
        returnCode = Integer.parseInt(returnCodeStr);
    } catch (NumberFormatException nfe) {
        throw new UdpConnectionException("Couldn't parse return code: " + returnCodeStr, nfe);
    }
    // Return string.
    index = data.indexOf('\n');
    if (index < 0) {
        returnString = data;
        data = "";
    } else {
        returnString = data.substring(0, index);
        data = data.substring(index + 1);
    }
    response = new UdpResponse(returnCode, returnString);
    // Entries?
    if (data.length() > 0) {
        entries = data.split("\\n", -1);
        for (int eIndex = 0; eIndex < entries.length; eIndex++) {
            if ((entries[eIndex].length() == 0) && (eIndex == entries.length - 1)) {
                break;
            }
            entry = new UdpResponseEntry();
            dataFields = entries[eIndex].split("\\|", -1);
            for (int dfIndex = 0; dfIndex < dataFields.length; dfIndex++) {
                entry.addDataField(new DataField(dataFields[dfIndex], charset));
            }
            response.entries.addElement(entry);
        }
        // MTU size problem.
        // TODO Implement a better solution for the MTU problem.
        if ((response.entries.size() > 0) && (packet.getLength() == 1400)) {
            /*
             * I assume if the packet length is equal to the MTU size, the
             * last entry is cut and must be removed.
             */
            index = response.entries.size() - 1;
            //            entry = response.entries.elementAt(index);
            //            data = entry.getMessageString();
            //            LOG.debug("last line = [" + data + ']');
            response.entries.removeElementAt(index);
        }
    }
    return response;
}

From source file:com.gamesalutes.utils.ByteUtils.java

/**
 * Reads all the bytes from the given input stream and stores them in the specified buffer.
 * If the input buffer is <code>null</code> or does not have the capacity to store all the input, a 
 * new buffer is created and returned.  The input stream is closed regardless of whether an
 * <code>IOException</code> is thrown.
 * //from  ww  w.  j  av  a  2s  .  co m
 * 
 * @param in the <code>InputStream</code> to read
 * @param buf a <code>ByteBuffer</code> to use for storage or <code>null</code> to just allocate a new one
 *        If <code>buf</code> is not large enough it will be expanded using {@link #growBuffer(ByteBuffer, int)}
 * @return the buffer containing the read data
 * @throws IOException
 */
public static ByteBuffer readBytes(InputStream in, ByteBuffer buf) throws IOException {
    try {
        if (buf == null)
            buf = ByteBuffer.allocate(READ_BUFFER_SIZE);

        // note the input position
        int startPos = buf.position();

        byte[] tmp = new byte[NETWORK_BYTE_SIZE];
        int read;
        // read until end of file
        while ((read = in.read(tmp)) > 0) {
            if (buf.remaining() < read) {
                buf = ByteUtils.growBuffer(buf, buf.limit() + (read - buf.remaining()));
            }
            buf.put(tmp, 0, read);
        }

        buf.flip();
        // reset starting position to be that of input buffer
        buf.position(startPos);
        return buf;
    } finally {
        MiscUtils.closeStream(in);
    }

}

From source file:com.github.neoio.net.message.staging.memory.MemoryMessageStaging.java

@Override
public int readTempReadBytes(ByteBuffer buffer) throws NetIOException {
    byte bytes[] = readTempStage.toByteArray();

    buffer.put(bytes, 0, readTempStageCount.getCount());

    return readTempStageCount.getCount();
}

From source file:com.github.neoio.net.message.staging.memory.MemoryMessageStaging.java

@Override
public int readTempWriteBytes(ByteBuffer buffer) throws NetIOException {
    byte bytes[] = writeTempStage.toByteArray();

    buffer.put(bytes, 0, writeTempStageCount.getCount());

    return bytes.length;
}

From source file:ByteString.java

public void store(ByteBuffer bb) {
    short n = 0;/*from   w w  w .  j av a 2  s  .  c  o  m*/
    if (bytes != null) {
        n = (short) bytes.length;
    }
    bb.putShort(n);
    if (n > 0) {
        bb.put(bytes, 0, n);
    }
}