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(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * Build an escaped telegram part for a slave answer
 *
 * @param slaveData/*from  w w w.j a v  a  2s . c om*/
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer buildPartSlave(byte[] slaveData) throws EBusTypeException {

    ByteBuffer buf = ByteBuffer.allocate(50);

    buf.put(EBusConsts.ACK_OK); // ACK

    // if payload available
    if (slaveData != null && slaveData.length > 0) {
        buf.put((byte) slaveData.length); // NN - Length

        // add the escaped bytes
        for (byte b : slaveData) {
            buf.put(escapeSymbol(b));
        }

        // calculate crc
        byte crc8 = EBusUtils.crc8(buf.array(), buf.position());

        // add the crc, maybe escaped
        buf.put(escapeSymbol(crc8));
    } else {
        // only set len = 0
        buf.put((byte) 0x00); // NN - Length
    }

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * Build a complete telegram for master/slave, master/master and broadcasts
 *
 * @param source//w  w  w  . ja  v a 2 s  .c  o m
 * @param target
 * @param command
 * @param masterData
 * @param slaveData
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer buildCompleteTelegram(byte source, byte target, byte[] command, byte[] masterData,
        byte[] slaveData) throws EBusTypeException {

    boolean isMastereMaster = EBusUtils.isMasterAddress(target);
    boolean isBroadcast = target == EBusConsts.BROADCAST_ADDRESS;
    boolean isMasterSlave = !isMastereMaster && !isBroadcast;

    ByteBuffer buf = ByteBuffer.allocate(50);
    buf.put(buildPartMasterTelegram(source, target, command, masterData));

    // if used compute a complete telegram
    if (isMasterSlave && slaveData != null) {
        ByteBuffer slaveTelegramPart = buildPartSlave(slaveData);
        buf.put(slaveTelegramPart);

        buf.put(EBusConsts.ACK_OK);
        buf.put(EBusConsts.SYN);
    }

    if (isMastereMaster) {
        buf.put(EBusConsts.ACK_OK);
        buf.put(EBusConsts.SYN);
    }

    if (isBroadcast) {
        buf.put(EBusConsts.SYN);
    }

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:de.csdev.ebus.command.EBusCommandUtils.java

/**
 * @param commandChannel/*  w  ww .j  a  v  a 2 s. c  om*/
 * @return
 */
public static ByteBuffer getMasterTelegramMask(IEBusCommandMethod commandChannel) {

    // byte len = 0;
    ByteBuffer buf = ByteBuffer.allocate(50);
    buf.put(commandChannel.getSourceAddress() == null ? (byte) 0x00 : (byte) 0xFF); // QQ - Source
    buf.put(commandChannel.getDestinationAddress() == null ? (byte) 0x00 : (byte) 0xFF); // ZZ - Target
    buf.put(new byte[] { (byte) 0xFF, (byte) 0xFF }); // PB SB - Command
    buf.put((byte) 0xFF); // NN - Length

    if (commandChannel.getMasterTypes() != null) {
        for (IEBusValue entry : commandChannel.getMasterTypes()) {
            IEBusType<?> type = entry.getType();

            if (entry.getName() == null && type instanceof EBusTypeBytes && entry.getDefaultValue() != null) {
                for (int i = 0; i < type.getTypeLength(); i++) {
                    buf.put((byte) 0xFF);
                }
            } else {
                for (int i = 0; i < type.getTypeLength(); i++) {
                    buf.put((byte) 0x00);

                }
            }
        }
    }

    buf.put((byte) 0x00); // Master CRC

    // set limit and reset position
    buf.limit(buf.position());
    buf.position(0);

    return buf;
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Creates an audio format chunk//from  w  ww  .j  a v a 2  s.co m
 */
public static ByteBuffer getFormatChunk(AudioFormat format) {
    ByteBuffer header = ByteBuffer.allocate(24).order(ByteOrder.LITTLE_ENDIAN);

    //Format descriptor
    header.put(FORMAT_CHUNK_ID.getBytes());
    header.putInt(FORMAT_CHUNK_LENGTH);
    header.putShort(FORMAT_UNCOMPRESSED_PCM);
    header.putShort((short) format.getChannels());
    header.putInt((int) format.getSampleRate());

    //Byte Rate = sample rate * channels * bits per sample / 8
    int frameByteRate = format.getChannels() * format.getSampleSizeInBits() / 8;
    int byteRate = (int) (format.getSampleRate() * frameByteRate);
    header.putInt(byteRate);

    //Block Align
    header.putShort((short) frameByteRate);

    //Bits per Sample
    header.putShort((short) format.getSampleSizeInBits());

    //Reset the buffer pointer to 0
    header.position(0);

    return header;
}

From source file:com.aerohive.nms.engine.admin.task.licensemgr.license.processor2.PacketUtil.java

public static byte[] join(Header header, byte[] content) {
    ByteBuffer buf = ByteBuffer.allocate(8192);

    byte[] outBytes;
    if (content.length == 0) {
        outBytes = new byte[0];
    } else {/*  ww  w. j  a v a  2 s.c  o m*/
        if (header.isSecretFlag()) {
            // encrypt data
            outBytes = encryptData(content);
        } else {
            outBytes = new byte[content.length];
            System.arraycopy(content, 0, outBytes, 0, content.length);
        }
    }
    buf.put(header.getType());
    buf.putInt(outBytes.length);
    buf.put(header.getProtocolVersion());
    buf.put(header.isSecretFlag() ? CommConst.Secret_Flag_Yes : CommConst.Secret_Flag_No);
    buf.put(outBytes);

    buf.flip();

    byte[] dst = new byte[buf.limit()];
    buf.get(dst);
    return dst;
}

From source file:Main.java

/**
 * @return/* ww w.ja va  2s . c o  m*/
 */
public static WritableByteChannel asWritableByteChannel(final ByteBuffer buffer) {
    return new WritableByteChannel() {

        private boolean open = true;

        public int write(ByteBuffer src) throws IOException {
            if (open == false) {
                throw new ClosedChannelException();
            }

            final int p = buffer.position();
            final int l = buffer.limit();
            final int r = src.remaining();

            buffer.limit(l + r);
            buffer.position(l);

            buffer.put(src);

            buffer.position(p);

            return r;
        }

        public void close() throws IOException {
            open = false;
        }

        public boolean isOpen() {
            return open;
        }

    };
}

From source file:com.googlecode.mp4parser.boxes.microsoft.XtraBox.java

private static void writeAsciiString(ByteBuffer dest, String s) {
    try {//w ww .jav a 2  s.  com
        dest.put(s.getBytes("US-ASCII"));
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Shouldn't happen", e);
    }
}

From source file:com.mymed.android.myjam.controller.HttpCall.java

/**
 * Given an InputStream reads the bytes as UTF8 chars and return a 
 * String./*  w  ww  .  j  ava 2 s. com*/
 * @param is Input stream.
 * @param length Length of the stream in bytes.
 * @return The string
 * @throws InternalBackEndException Format is not correct or the length less then the real wrong.
 */
private static String convertStreamToString(InputStream is, long length) throws InternalClientException {
    String streamString;
    if (length > Integer.MAX_VALUE)
        throw new InternalClientException("Wrong Content");
    int byteLength = (int) length;
    try {
        if (byteLength > 0) {
            ByteBuffer byteBuff = ByteBuffer.allocate(byteLength);
            int currByte;
            while ((currByte = is.read()) != -1) {
                byteBuff.put((byte) currByte);
            }
            byteBuff.compact();
            final CharBuffer charBuf = CHARSET.newDecoder().decode(byteBuff);
            streamString = charBuf.toString();
            return streamString;
        } else {
            BufferedReader buffRead = new BufferedReader(
                    new InputStreamReader(is, Charset.forName(CHARSET_NAME)));
            StringBuilder sb = new StringBuilder();
            String line;
            while ((line = buffRead.readLine()) != null) {
                sb.append(line + "\n");
            }
            return sb.toString();
        }
    } catch (IOException e) {
        throw new InternalClientException("Wrong content");
    } catch (BufferOverflowException e) {
        throw new InternalClientException("Wrong length");
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

From source file:com.sitewhere.hbase.device.HBaseDeviceEvent.java

/**
 * Get column qualifier for storing the event.
 * //from   w ww . j av  a 2 s .com
 * @param type
 * @param time
 * @return
 */
public static byte[] getQualifier(DeviceAssignmentRecordType eventType, long time) {
    time = time / 1000;
    long offset = time % BUCKET_INTERVAL;
    byte[] offsetBytes = Bytes.toBytes(offset);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.put((byte) ~offsetBytes[5]);
    buffer.put((byte) ~offsetBytes[6]);
    buffer.put((byte) ~offsetBytes[7]);
    buffer.put(eventType.getType());
    return buffer.array();
}

From source file:jsave.Utils.java

public static int read_long(final RandomAccessFile raf) throws IOException {
    byte[] data = new byte[4];
    raf.read(data);// w  w  w .  j  a v  a  2  s . com
    ByteBuffer bb = ByteBuffer.allocate(data.length);
    bb.put(data);
    return bb.getInt(0);
}