Example usage for java.nio ByteBuffer allocate

List of usage examples for java.nio ByteBuffer allocate

Introduction

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

Prototype

public static ByteBuffer allocate(int capacity) 

Source Link

Document

Creates a byte buffer based on a newly allocated byte array.

Usage

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

@Test
public void test_tempRead() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.flip();//from w ww .j a  v a 2 s  .  c om
    staging.writeTempReadBytes(buffer);
    Assert.assertTrue(staging.hasTempReadBytes());

    buffer.clear();
    staging.readTempReadBytes(buffer);
    Assert.assertEquals("Hello World",
            new String(ArrayUtils.subarray(buffer.array(), 0, "Hello World".getBytes().length)));
    staging.resetTempReadBytes();

    Assert.assertFalse(staging.hasTempReadBytes());
}

From source file:Main.java

public static String completeJweFromSIM(String jweSIM) {
    // android.os.Debug.waitForDebugger();

    try {//w  ww  .  j a  v a2s  .  co m
        if (jweSIM != null && jweSIM.length() > 0) {
            String parts[] = jweSIM.split("\\.");
            ;
            if (parts != null && parts.length == 5) {
                // retrieve hmac key
                byte hmac_key[] = Base64.decode(parts[4], Base64.URL_SAFE);
                if (hmac_key != null && hmac_key.length == 16) {
                    // init hash instance
                    Mac hmac = Mac.getInstance("HmacSHA256", "SC");
                    hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));

                    byte[] aad = parts[0].getBytes();
                    long al = aad.length * 8;
                    byte[] iv_key = decodeB64(parts[2]);
                    byte[] cryptedBytes = decodeB64(parts[3]);

                    // build data to hash
                    byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
                    int offset = 0;
                    System.arraycopy(aad, offset, hmacData, 0, aad.length);
                    offset += aad.length;
                    System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
                    offset += iv_key.length;
                    System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
                    offset += cryptedBytes.length;
                    ByteBuffer buffer = ByteBuffer.allocate(8);
                    buffer.putLong(al);
                    System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

                    // compute hac value
                    byte[] hmacValue = hmac.doFinal(hmacData);
                    // authentication tag
                    byte[] auth_tag = Arrays.copyOf(hmacValue, 16);
                    String auth_tag64 = encodeB64(auth_tag);

                    // A.2.7. Complete Representation
                    String finalString = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3] + "."
                            + auth_tag64;

                    //                  // just for verification
                    //                  byte jwt64 [] = decryptJWE(finalString, RsaKeyTim.privRsaKey);
                    //                  if(jwt64!=null) {
                    //                     String jws = new String(jwt64);
                    //                     Log.d("completeJweFromSIM", "jws verify Key TIM :"+verifyJWS(jws,RsaKeyTim.pubRsaKey));
                    //                  }

                    return finalString;
                }
            }
            // 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.alibaba.otter.shared.common.utils.ByteUtils.java

public static int bytes2int(byte[] b) {
    ByteBuffer buf = ByteBuffer.allocate(4);
    buf.put(b);/*www  .j ava 2  s  .c  o m*/
    buf.flip();
    return buf.getInt();
}

From source file:me.whitmarbut.mfa.TOTP.java

private byte[] getHmac(int timestamp, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec key_spec = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key_spec);/*from   w  w  w.  j a  v  a  2s . c  o m*/
    byte[] bin_timestamp = ByteBuffer.allocate(4).putInt(timestamp).array();

    ByteBuffer bbuff = ByteBuffer.allocate(8);
    bbuff.putInt(0); //Left pad 4 bytes to make a 64 bit int
    bbuff.putInt(timestamp);

    return mac.doFinal(bbuff.array());
}

From source file:backtype.storm.messaging.TaskMessage.java

public ByteBuffer serialize() {
    ByteBuffer bb = ByteBuffer.allocate(_message.length + 4);
    bb.putShort((short) _task);
    bb.putShort(remoteTuple);/*w  w  w .j  av a2  s. co m*/
    bb.put(_message);
    return bb;
}

From source file:com.talis.storage.s3.S3ObjectFactoryTest.java

@Before
public void setup() {
    bucketname = UUID.randomUUID().toString();
    factory = new S3ObjectFactory(bucketname);
    buffer = ByteBuffer.allocate(1024);
    buffer.put(entity);//from   w  w w  .j a  v a2  s .c  o m
}

From source file:net.darkmist.alib.io.BufferUtil.java

/**
 * Allocate a buffer and fill it from a channel. The returned
 * buffer will be rewound to the begining.
 * @return Buffer containing size bytes from the channel.
 * @throws IOException if the channel read does.
 * @throws EOFException if a end of stream is encountered
 *    before the full size is read./*from w ww. ja v a2s .  com*/
 */
public static ByteBuffer allocateAndReadAll(int size, ReadableByteChannel channel) throws IOException {
    ByteBuffer buf = ByteBuffer.allocate(size);
    int justRead;
    int totalRead = 0;

    // FIXME, this will be a tight loop if the channel is non-blocking...
    while (totalRead < size) {
        logger.debug("reading totalRead={}", totalRead);
        if ((justRead = channel.read(buf)) < 0)
            throw new EOFException("Unexpected end of stream after reading " + totalRead + " bytes");
        totalRead += justRead;
    }
    buf.rewind();
    return buf;
}

From source file:ru.jts_dev.common.tcp.ProtocolByteArrayLengthHeaderSerializer.java

@Override
protected void writeHeader(OutputStream outputStream, int length) throws IOException {
    ByteBuffer lengthPart = ByteBuffer.allocate(this.headerSize).order(LITTLE_ENDIAN);
    length += headerSize; // Protocol thing, length represent header size + data size
    switch (this.headerSize) {
    case HEADER_SIZE_INT:
        lengthPart.putInt(length);/*ww  w . java2s.c o m*/
        break;
    case HEADER_SIZE_UNSIGNED_BYTE:
        if (length > 0xff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.put((byte) length);
        break;
    case HEADER_SIZE_UNSIGNED_SHORT:
        if (length > 0xffff) {
            throw new IllegalArgumentException(
                    "Length header:" + headerSize + " too short to accommodate message length:" + length);
        }
        lengthPart.putShort((short) length);
        break;
    default:
        throw new IllegalArgumentException("Bad header size:" + headerSize);
    }
    outputStream.write(lengthPart.array());
}

From source file:Main.java

public static byte[] makeFontBitmap(String font, String code, int size, float[] arrayOfPos) {
    Canvas c = new Canvas();
    Paint p = new Paint();
    float density = context.getResources().getDisplayMetrics().density;
    //        Log.v(TAG, String.format("makeFontBitmap called(Java): font=%s code=%s density=%f", font, code, density));
    p.setTextSize((float) size * density);
    p.setAntiAlias(true);/*from   ww w  .ja v  a  2s.  c  o  m*/

    Rect textBounds = new Rect();
    p.getTextBounds(code, 0, code.length(), textBounds);
    //        Log.v(TAG, String.format("makeFontBitmap textBounds: %d,%d,%d,%d", textBounds.left, textBounds.top, textBounds.right, textBounds.bottom));

    Rect textBoundsAxA = new Rect();
    String axa = String.format("A%sA", code);
    p.getTextBounds(axa, 0, axa.length(), textBoundsAxA);
    Rect textBoundsAA = new Rect();
    String aa = "AA";
    p.getTextBounds(aa, 0, aa.length(), textBoundsAA);

    // cache.distDelta = Vec2(0, 0);
    arrayOfPos[0] = textBounds.left;
    arrayOfPos[1] = textBounds.top;

    // cache.srcWidth = Vec2(16, 16);
    arrayOfPos[2] = textBounds.width();
    arrayOfPos[3] = textBounds.height();

    // cache.step = 16;
    //      arrayOfPos[4] = textBounds.width() + 1;
    arrayOfPos[4] = textBoundsAxA.width() - textBoundsAA.width();

    if (textBounds.width() == 0 || textBounds.height() == 0) {
        Log.v(TAG, "makeFontBitmap: empty");
        return null;
    }

    Bitmap b = Bitmap.createBitmap(textBounds.width(), textBounds.height(), Bitmap.Config.ARGB_8888);
    c.setBitmap(b);

    Rect r = new Rect(0, 0, textBounds.width(), textBounds.height());
    //      p.setColor(Color.RED);
    p.setARGB(0, 0, 0, 0);
    c.drawRect(r, p);
    p.setARGB(255, 255, 255, 255);

    //        Log.v(TAG, "makeFontBitmap: drawText");
    c.drawText(code, -textBounds.left, -textBounds.top, p);
    //        Log.v(TAG, String.format("makeFontBitmap: w=%.2f h=%.2f", arrayOfPos[2], arrayOfPos[3]));

    ByteBuffer buf = ByteBuffer.allocate(textBounds.width() * textBounds.height() * 4);
    //        Log.v(TAG, String.format("makeFontBitmap: b.getRowBytes() %d", b.getRowBytes()));
    buf.position(0);
    b.copyPixelsToBuffer(buf);
    //        Log.v(TAG, String.format("makeFontBitmap results: capacity=%d", buf.capacity()));

    return buf.array();
}

From source file:biz.karms.sinkit.ejb.util.CIDRUtils.java

public static ImmutablePair<String, String> getStartEndAddresses(final String cidr)
        throws UnknownHostException {
    //TODO: This is silly. Refactor CIDRUtils so as to accept actual IPs as well as subnets.
    //TODO: Validate the thing before processing. Guava?
    final String fixedCIDR;
    if (!cidr.contains("/")) {
        //IPv6? Hmmm...
        if (cidr.contains(":")) {
            fixedCIDR = cidr + "/128";
        } else {//www  . j a va 2  s .  c  o m
            fixedCIDR = cidr + "/32";
        }
    } else {
        fixedCIDR = cidr;
    }
    final int index = fixedCIDR.indexOf("/");
    final InetAddress inetAddress = InetAddress.getByName(fixedCIDR.substring(0, index));
    final int prefixLength = Integer.parseInt(fixedCIDR.substring(index + 1));

    final ByteBuffer maskBuffer;
    if (inetAddress.getAddress().length == 4) {
        maskBuffer = ByteBuffer.allocate(4).putInt(-1);
    } else {
        maskBuffer = ByteBuffer.allocate(16).putLong(-1L).putLong(-1L);
    }

    final BigInteger mask = (new BigInteger(1, maskBuffer.array())).not().shiftRight(prefixLength);
    final ByteBuffer buffer = ByteBuffer.wrap(inetAddress.getAddress());
    final BigInteger ipVal = new BigInteger(1, buffer.array());
    final BigInteger startIp = ipVal.and(mask);
    final BigInteger endIp = startIp.add(mask.not());

    return new ImmutablePair<>(String.format("%040d", startIp), String.format("%040d", endIp));
}