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:tachyon.master.RawTablesTest.java

@Test
public void writeImageTest() throws IOException, TachyonException {
    // crate the RawTables, byte buffers, and output streams
    RawTables rt = new RawTables(new TachyonConf());
    ByteBuffer bb1 = ByteBuffer.allocate(1);
    ByteBuffer bb2 = ByteBuffer.allocate(1);
    ByteBuffer bb3 = ByteBuffer.allocate(1);

    ByteArrayOutputStream os = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(os);
    ObjectMapper mapper = JsonObject.createObjectMapper();
    ObjectWriter writer = mapper.writer();

    // add elements to the RawTables
    rt.addRawTable(0, 1, bb1);/*from   www .  ja va2s  .  c om*/
    rt.addRawTable(1, 1, bb2);
    rt.addRawTable(2, 1, bb3);

    // write the image
    rt.writeImage(writer, dos);

    List<Integer> ids = Arrays.asList(0, 1, 2);
    List<Integer> columns = Arrays.asList(1, 1, 1);
    List<ByteBuffer> data = Arrays.asList(bb1, bb2, bb3);

    // decode the written bytes
    ImageElement decoded = mapper.readValue(os.toByteArray(), ImageElement.class);

    // test the decoded ImageElement
    Assert.assertEquals(ids, decoded.get("ids", new TypeReference<List<Integer>>() {
    }));
    Assert.assertEquals(columns, decoded.get("columns", new TypeReference<List<Integer>>() {
    }));
    Assert.assertEquals(data, decoded.get("data", new TypeReference<List<ByteBuffer>>() {
    }));
}

From source file:io.blobkeeper.file.util.FileUtils.java

public static boolean isFileEmpty(@NotNull File file, @NotNull IndexElt elt) {
    ByteBuffer fourBytes = ByteBuffer.allocate(4);
    try {/*from   w  w  w  .ja  v  a2s  .c om*/
        file.getFileChannel().read(fourBytes, elt.getOffset());
    } catch (IOException e) {
        log.error("Can't read blob file", e);
        throw new IllegalArgumentException(e);
    }

    fourBytes.flip();
    for (byte b : fourBytes.array()) {
        if (b != 0) {
            return false;
        }
    }

    return true;
}

From source file:internal.diff.aws.service.AmazonS3ETagFileChecksumServiceImpl.java

@Override
public String calculateChecksum(Path file) throws IOException {

    long fileSize = Files.size(file);

    int parts = (int) (fileSize / S3_MULTIPART_SIZE_LIMIT_IN_BYTES);
    parts += fileSize % S3_MULTIPART_SIZE_LIMIT_IN_BYTES > 0 ? 1 : 0;

    ByteBuffer checksumBuffer = ByteBuffer.allocate(parts * 16);

    SeekableByteChannel byteChannel = Files.newByteChannel(file);

    for (int part = 0; part < parts; part++) {

        int partSizeInBytes;

        if (part < parts - 1 || fileSize % S3_MULTIPART_SIZE_LIMIT_IN_BYTES == 0) {
            partSizeInBytes = S3_MULTIPART_SIZE_LIMIT_IN_BYTES;
        } else {/*w  w w  . j  a  v a2  s.  c  o m*/
            partSizeInBytes = (int) (fileSize % S3_MULTIPART_SIZE_LIMIT_IN_BYTES);
        }

        ByteBuffer partBuffer = ByteBuffer.allocate(partSizeInBytes);

        boolean endOfFile;
        do {
            endOfFile = byteChannel.read(partBuffer) == -1;
        } while (!endOfFile && partBuffer.hasRemaining());

        checksumBuffer.put(DigestUtils.md5(partBuffer.array()));
    }

    if (parts > 1) {
        return DigestUtils.md5Hex(checksumBuffer.array()) + "-" + parts;
    } else {
        return Hex.encodeHexString(checksumBuffer.array());
    }
}

From source file:edu.kit.trufflehog.model.network.MacAddress.java

public MacAddress(long address) throws InvalidMACAddress {

    this.address = address;

    if (this.address > 0xFFFFFFFFFFFFL || this.address < 0) {
        throw new InvalidMACAddress(address);
    }/*from  w  w w .  j a  va2 s  .  com*/

    hashcode = (new Long(address)).hashCode();
    // transform to byte array
    final byte[] extractedBytes = ByteBuffer.allocate(8).putLong(address).array();
    bytes = Arrays.copyOfRange(extractedBytes, 2, 8);

    // set multicast bit
    isMulticast = (bytes[0] & 1) == 1;

    // set string representation
    final List<Byte> bytes = Arrays.asList(ArrayUtils.toObject(toByteArray()));
    addressString = bytes.stream().map(b -> String.format("%02x", b)).collect(Collectors.joining(":"));
}

From source file:Main.java

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

    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);
    //      ByteBuffer buf = ByteBuffer.allocate(b.getRowBytes());
    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()));

    //      byte bytes[] = buf.array();
    //      for (int i = 0; i < size * size * 2; i++)
    //         bytes[i] = (byte)(Math.random() * 255);
    return buf.array();
}

From source file:Main.java

@Override
public void completed(AsynchronousSocketChannel client, Attachment attach) {
    try {/*ww  w.  j av a2  s . c  o m*/
        SocketAddress clientAddr = client.getRemoteAddress();
        System.out.format("Accepted a  connection from  %s%n", clientAddr);
        attach.server.accept(attach, this);
        ReadWriteHandler rwHandler = new ReadWriteHandler();
        Attachment newAttach = new Attachment();
        newAttach.server = attach.server;
        newAttach.client = client;
        newAttach.buffer = ByteBuffer.allocate(2048);
        newAttach.isRead = true;
        newAttach.clientAddr = clientAddr;
        client.read(newAttach.buffer, newAttach, rwHandler);
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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

@Test
public void roundTripS3ObjectSerialization() throws Exception {
    ByteArrayOutputStream tmp = new ByteArrayOutputStream();
    ObjectOutputStream out = new ObjectOutputStream(tmp);

    byte[] bytes = ("When replying to any emails you have prior to migration "
            + "(ie any in your inbox before you have been migrated) "
            + "you will need to change the way you reply to them").getBytes();

    ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
    buffer.put(bytes);//from ww  w  .j av a  2 s .com

    S3ObjectFactory factory = new S3ObjectFactory("bucket");
    S3Object original = factory.newObject("foo", 0, MediaType.TEXT_PLAIN_TYPE, buffer);

    out.writeObject(original);
    out.flush();
    out.close();

    byte[] serialized = tmp.toByteArray();

    ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(serialized));
    S3Object clone = (S3Object) in.readObject();

    assertObjectsEqual(original, clone);
}

From source file:Main.java

/**
 * Creates the Uri string with embedded expansion codes.
 *
 * @param uri to be encoded//  w  w w.  j a  v a2 s .  c o m
 * @return the Uri string with expansion codes.
 */
public static byte[] encodeUri(String uri) {
    if (uri == null || uri.length() == 0) {
        Log.i(TAG, "null or empty uri");
        return new byte[0];
    }
    ByteBuffer bb = ByteBuffer.allocate(uri.length());
    // UUIDs are ordered as byte array, which means most significant first
    bb.order(ByteOrder.BIG_ENDIAN);
    int position = 0;

    // Add the byte code for the scheme or return null if none
    Byte schemeCode = encodeUriScheme(uri);
    if (schemeCode == null) {
        Log.i(TAG, "null scheme code");
        return null;
    }
    String scheme = URI_SCHEMES.get(schemeCode);
    bb.put(schemeCode);
    position += scheme.length();

    if (URLUtil.isNetworkUrl(scheme)) {
        Log.i(TAG, "is network URL");
        return encodeUrl(uri, position, bb);
    } else if ("urn:uuid:".equals(scheme)) {
        Log.i(TAG, "is UUID");
        return encodeUrnUuid(uri, position, bb);
    }
    return null;
}

From source file:com.hazelcast.simulator.probes.xml.HistogramConverter.java

@Override
public void marshal(Object object, HierarchicalStreamWriter writer, MarshallingContext marshallingContext) {
    Histogram histogram = (Histogram) object;
    int size = histogram.getNeededByteBufferCapacity();
    ByteBuffer byteBuffer = ByteBuffer.allocate(size);
    int bytesWritten = histogram.encodeIntoCompressedByteBuffer(byteBuffer);
    byteBuffer.rewind();//from w w w  .  ja va 2  s  .  c  o m
    byteBuffer.limit(bytesWritten);
    String encodedHistogram = encodeBase64String(byteBuffer.array());

    writer.setValue(encodedHistogram);
}

From source file:de.kapsi.net.daap.nio.DaapRequestReaderNIO.java

/** Creates a new instance of DaapRequestReader */
public DaapRequestReaderNIO(DaapConnectionNIO connection) {

    this.connection = connection;

    in = ByteBuffer.allocate(1024);
    in.clear();//from w  ww  . j a v  a 2  s  .c o  m
    in.flip();

    lineReader = new DaapLineReaderNIO(connection.getChannel());
    headers = new ArrayList();
    pending = new LinkedList();
}