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:Main.java

/**
 * Decodes the specified URL as per RFC 3986, i.e. transforms
 * percent-encoded octets to characters by decoding with the UTF-8 character
 * set. This function is primarily intended for usage with
 * {@link URL} which unfortunately does not enforce proper URLs. As
 * such, this method will leniently accept invalid characters or malformed
 * percent-encoded octets and simply pass them literally through to the
 * result string. Except for rare edge cases, this will make unencoded URLs
 * pass through unaltered./* ww w  .j  a v a2 s.co m*/
 *
 * @param url The URL to decode, may be {@code null}.
 * @return The decoded URL or {@code null} if the input was
 * {@code null}.
 */
static String decodeUrl(String url) {
    String decoded = url;
    if (url != null && url.indexOf('%') >= 0) {
        int n = url.length();
        StringBuffer buffer = new StringBuffer();
        ByteBuffer bytes = ByteBuffer.allocate(n);
        for (int i = 0; i < n;) {
            if (url.charAt(i) == '%') {
                try {
                    do {
                        byte octet = (byte) Integer.parseInt(url.substring(i + 1, i + 3), 16);
                        bytes.put(octet);
                        i += 3;
                    } while (i < n && url.charAt(i) == '%');
                    continue;
                } catch (RuntimeException e) {
                    // malformed percent-encoded octet, fall through and
                    // append characters literally
                } finally {
                    if (bytes.position() > 0) {
                        bytes.flip();
                        buffer.append(UTF8.decode(bytes).toString());
                        bytes.clear();
                    }
                }
            }
            buffer.append(url.charAt(i++));
        }
        decoded = buffer.toString();
    }
    return decoded;
}

From source file:com.microsoft.Malmo.Utils.TextureHelper.java

public static int loadShader(String filename, int shaderType) throws IOException {
    int shaderID = -1;
    InputStream stream = MalmoMod.class.getClassLoader().getResourceAsStream(filename);
    if (stream == null) {
        System.out.println("Cannot find shader.");
        return -1;
    }// w w  w. java 2  s.c  o m
    try {
        byte[] abyte = IOUtils.toByteArray((InputStream) (new BufferedInputStream(stream)));
        ByteBuffer bytebuffer = BufferUtils.createByteBuffer(abyte.length);
        bytebuffer.put(abyte);
        bytebuffer.position(0);
        shaderID = OpenGlHelper.glCreateShader(shaderType);
        OpenGlHelper.glShaderSource(shaderID, bytebuffer);
        OpenGlHelper.glCompileShader(shaderID);

        if (OpenGlHelper.glGetShaderi(shaderID, OpenGlHelper.GL_COMPILE_STATUS) == 0) {
            String s = StringUtils.trim(OpenGlHelper.glGetShaderInfoLog(shaderID, 32768));
            JsonException jsonexception = new JsonException("Couldn\'t compile shader program: " + s);
            throw jsonexception;
        }
    } finally {
        IOUtils.closeQuietly(stream);
    }
    return shaderID;
}

From source file:com.openteach.diamond.network.waverider.session.DefaultSession.java

public static Command makeGreetCommand() {
    String HELLO = "Hello Master";
    ByteBuffer buffer = ByteBuffer.allocate(HELLO.getBytes().length);
    buffer.put(HELLO.getBytes());
    buffer.flip();//from ww w .j a  v a2 s  .c o  m
    Command command = new Command(1L, buffer);
    return command;
}

From source file:Main.java

public static ByteBuffer clone(final ByteBuffer buf) {
    if (buf == null) {
        return null;
    }/*from  w w w. j a v a  2s .  c  o m*/
    buf.rewind();

    final ByteBuffer copy;
    if (buf.isDirect()) {
        copy = createByteBuffer(buf.limit());
    } else {
        copy = createByteBufferOnHeap(buf.limit());
    }
    copy.put(buf);

    return copy;
}

From source file:byps.BWire.java

/**
 * Reads a ByteBuffer from an InputStream
 * Closes the InputStream.//from  ww  w.j  a va  2  s .c o m
 * @param is
 * @return
 * @throws IOException
 */
public static ByteBuffer bufferFromStream(InputStream is, Boolean gzip) throws IOException {
    if (is == null)
        return null;
    try {
        ByteBuffer ibuf = ByteBuffer.allocate(10 * 1000);

        if (gzip != null) {
            if (gzip) {
                is = new GZIPInputStream(is);
            }
        } else {
            if (!is.markSupported())
                is = new BufferedInputStream(is, 2);
            is.mark(2);
            int magic = is.read() | (is.read() << 8);
            is.reset();
            if (magic == GZIPInputStream.GZIP_MAGIC) {
                is = new GZIPInputStream(is);
            }
        }

        ReadableByteChannel rch = Channels.newChannel(is);
        while (rch.read(ibuf) != -1) {
            if (ibuf.remaining() == 0) {
                ByteBuffer nbuf = ByteBuffer.allocate(ibuf.capacity() * 2);
                ibuf.flip();
                nbuf.put(ibuf);
                ibuf = nbuf;
            }
        }

        ibuf.flip();
        return ibuf;
    } finally {
        is.close();
    }
}

From source file:jBittorrentAPI.utils.Utils.java

/**
 * Concatenate the 2 byte arrays//  w  w  w . ja v a 2  s.co m
 * @param a byte[]
 * @param b byte[]
 * @return byte[]
 */
public static byte[] concat2(byte[] a, byte[] b) {
    ByteBuffer bb = ByteBuffer.allocate(a.length + b.length);
    bb.put(a);
    bb.put(b);
    return bb.array();
}

From source file:com.alibaba.rocketmq.common.MixAll.java

public static long createBrokerId(final String ip, final int port) {
    InetSocketAddress isa = new InetSocketAddress(ip, port);
    byte[] ipArray = isa.getAddress().getAddress();
    ByteBuffer bb = ByteBuffer.allocate(8);
    bb.put(ipArray);
    bb.putInt(port);/* w ww .ja v  a  2s  .  c  om*/
    long value = bb.getLong(0);
    return Math.abs(value);
}

From source file:Main.java

/**
 * Decode/unescape a portion of a URL, to use with the query part ensure {@code plusAsBlank} is true.
 *
 * @param content     the portion to decode
 * @param charset     the charset to use
 * @param plusAsBlank if {@code true}, then convert '+' to space (e.g. for www-url-form-encoded content), otherwise leave as is.
 * @return encoded string/*w  w w.  j  a v  a 2  s . co  m*/
 */
private static String urldecode(final String content, final Charset charset, final boolean plusAsBlank) {
    if (content == null) {
        return null;
    }
    ByteBuffer bb = ByteBuffer.allocate(content.length());
    CharBuffer cb = CharBuffer.wrap(content);
    while (cb.hasRemaining()) {
        char c = cb.get();
        if (c == '%' && cb.remaining() >= 2) {
            char uc = cb.get();
            char lc = cb.get();
            int u = Character.digit(uc, 16);
            int l = Character.digit(lc, 16);
            if (u != -1 && l != -1) {
                bb.put((byte) ((u << 4) + l));
            } else {
                bb.put((byte) '%');
                bb.put((byte) uc);
                bb.put((byte) lc);
            }
        } else if (plusAsBlank && c == '+') {
            bb.put((byte) ' ');
        } else {
            bb.put((byte) c);
        }
    }
    bb.flip();
    return charset.decode(bb).toString();
}

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

/**
 * Builds an escaped master telegram part or if slaveData is used a complete telegram incl. master ACK and SYN
 *
 * @param source//from  ww w  . j  ava  2 s. co m
 * @param target
 * @param command
 * @param masterData
 * @return
 * @throws EBusTypeException
 */
public static ByteBuffer buildPartMasterTelegram(byte source, byte target, byte[] command, byte[] masterData)
        throws EBusTypeException {

    ByteBuffer buf = ByteBuffer.allocate(50);

    buf.put(source); // QQ - Source
    buf.put(target); // ZZ - Target
    buf.put(command); // PB SB - Command
    buf.put((byte) masterData.length); // NN - Length, will be set later

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

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

    buf.put(escapeSymbol(crc8));

    // 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 a wave file header with a format descriptor chunk
 *//*www .  ja  v  a 2  s  .co m*/
public static ByteBuffer getWaveHeader(AudioFormat format) {
    ByteBuffer header = ByteBuffer.allocate(12).order(ByteOrder.LITTLE_ENDIAN);

    //RIFF/WAVE header and size
    header.put(RIFF_ID.getBytes());
    header.putInt(INITIAL_TOTAL_LENGTH);
    header.put(WAVE_ID.getBytes());

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

    return header;
}