Example usage for java.nio ByteBuffer allocateDirect

List of usage examples for java.nio ByteBuffer allocateDirect

Introduction

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

Prototype

public static ByteBuffer allocateDirect(int capacity) 

Source Link

Document

Creates a direct byte buffer based on a newly allocated memory block.

Usage

From source file:org.eclipse.swt.snippets.Snippet341.java

static void capture(GLCanvas glCanvas) {
    final int PAD = 4;
    Display display = glCanvas.getDisplay();
    Rectangle bounds = glCanvas.getBounds();
    int size = bounds.width * PAD * bounds.height;

    ByteBuffer buffer = ByteBuffer.allocateDirect(size);
    GL11.glReadPixels(0, 0, bounds.width, bounds.height, GL11.GL_RGBA, GL11.GL_UNSIGNED_BYTE, buffer);
    byte[] bytes = new byte[size];
    buffer.get(bytes);/*from   w  ww . j av a 2 s  .  c om*/
    /*
     * In OpenGL (0,0) is at the bottom-left corner, and y values ascend in the upward
     * direction.  This is opposite to SWT which defines (0,0) to be at the top-left
     * corner with y values ascendingin the downwards direction.  Re-order the OpenGL-
     * provided bytes to SWT's expected order so that the Image will not appear inverted.
     */
    byte[] temp = new byte[bytes.length];
    for (int i = 0; i < bytes.length; i += bounds.width * PAD) {
        System.arraycopy(bytes, bytes.length - i - bounds.width * PAD, temp, i, bounds.width * PAD);
    }
    bytes = temp;
    ImageData data = new ImageData(bounds.width, bounds.height, 32,
            new PaletteData(0xFF000000, 0xFF0000, 0xFF00), PAD, bytes);
    final Image image = new Image(display, data);

    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    Canvas canvas = new Canvas(shell, SWT.NONE);
    canvas.setLayoutData(new GridData(bounds.width, bounds.height));
    canvas.addListener(SWT.Paint, event -> event.gc.drawImage(image, 0, 0));
    shell.pack();
    shell.open();
    shell.addListener(SWT.Dispose, event -> image.dispose());
}

From source file:it.geosolutions.opensdi2.service.impl.FileUploadServiceImpl.java

/**
 * Create a temporal file with a byte array
 * /*from  ww  w.j  ava 2  s .c o  m*/
 * @param key of the file
 * @param bytes to write
 * @param i index by the file name
 * @return absolute path to the file
 * @throws IOException
 */
public String createTemporalFile(String key, byte[] bytes, int i) throws IOException {

    String filePath = temporaryFolder + File.separator + key;

    try {

        // write bytes
        File tmpFile = new File(filePath);

        if (LOGGER.isTraceEnabled()) {
            LOGGER.trace("Appending bytes to " + tmpFile.getAbsolutePath());
        }

        // File channel to append bytes
        @SuppressWarnings("resource")
        FileChannel channel = new FileOutputStream(tmpFile, true).getChannel();
        ByteBuffer buf = ByteBuffer.allocateDirect((int) bytes.length);

        // put bytes
        buf.put(bytes);

        // Flips this buffer.  The limit is set to the current position and then
        // the position is set to zero.  If the mark is defined then it is discarded.
        buf.flip();

        // Writes a sequence of bytes to this channel from the given buffer.
        channel.write(buf);

        // close the channel
        channel.close();

    } catch (IOException e) {
        LOGGER.error("Error writing file bytes", e);
    }

    return filePath;
}

From source file:com.kentdisplays.synccardboarddemo.Page.java

/**
 * Sets up the drawing object data for use in an OpenGL ES context.
 *
 * @param is InputStream to the page to load the path data from.
 *///from   w  ww . j ava2 s .c om
public Page(InputStream is, int glProgram, int direction) {

    this.mModel = new float[16];
    this.mGlProgram = glProgram;

    // Calculate the coordinates from the given path.
    ArrayList<Path> paths = pathsFromSamplePageInputStream(is);
    float finalCoords[] = {};
    float finalNormals[] = {};
    float finalColors[] = {};
    mNumberOfPaths = paths.size();
    for (int i = 0; i < mNumberOfPaths; i++) {
        Path path = paths.get(i);
        float x1 = (path.x1 / 13942 * 2) - 1;
        float y1 = (path.y1 / 20280 * 2) - 1;
        float x2 = (path.x2 / 13942 * 2) - 1;
        float y2 = (path.y2 / 20280 * 2) - 1;
        float width = path.width / 3000;
        width = width < 0.013f ? 0.013f : width; // Width should be at least 0.013

        float distance = (float) Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
        float angle = (float) Math.PI / 2 - (float) Math.asin((x2 - x1) / distance);
        float xdiff = (width / 2) * (float) Math.sin(angle);
        float ydiff = (width / 2) * (float) Math.cos(angle);

        float coords[] = { x1 - xdiff, y1 - ydiff, 1.0f, // top left
                x2 - xdiff, y2 - ydiff, 1.0f, // bottom left
                x1 + xdiff, y1 + ydiff, 1.0f, // top right
                x2 - xdiff, y2 - ydiff, 1.0f, // bottom left
                x2 + xdiff, y2 + ydiff, 1.0f, // bottom right
                x1 + xdiff, y1 + ydiff, 1.0f, // top right
        };

        float normals[] = { 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f, 1.0f, 0.0f, 0.0f,
                1.0f, 0.0f, 0.0f, 1.0f, };

        float colors[] = { 0.2f, 0.709803922f, 0.898039216f, 1.0f, 0.2f, 0.709803922f, 0.898039216f, 1.0f, 0.2f,
                0.709803922f, 0.898039216f, 1.0f, 0.2f, 0.709803922f, 0.898039216f, 1.0f, 0.2f, 0.709803922f,
                0.898039216f, 1.0f, 0.2f, 0.709803922f, 0.898039216f, 1.0f, };

        finalCoords = Floats.concat(finalCoords, coords);
        finalNormals = Floats.concat(finalNormals, normals);
        finalColors = Floats.concat(finalColors, colors);
    }

    ByteBuffer bbVertices = ByteBuffer.allocateDirect(finalCoords.length * 4);
    bbVertices.order(ByteOrder.nativeOrder());
    mPageVertices = bbVertices.asFloatBuffer();
    mPageVertices.put(finalCoords);
    mPageVertices.position(0);

    ByteBuffer bbNormals = ByteBuffer.allocateDirect(finalNormals.length * 4);
    bbNormals.order(ByteOrder.nativeOrder());
    mPageNormals = bbNormals.asFloatBuffer();
    mPageNormals.put(finalNormals);
    mPageNormals.position(0);

    ByteBuffer bbColors = ByteBuffer.allocateDirect(finalColors.length * 4);
    bbColors.order(ByteOrder.nativeOrder());
    mPageColors = bbColors.asFloatBuffer();
    mPageColors.put(finalColors);
    mPageColors.position(0);

    // Correctly place the page in the world.
    Matrix.setIdentityM(mModel, 0);
    switch (direction) {
    case 0:
        Matrix.translateM(mModel, 0, 0, 0, -mDistance); //Front.
        break;
    case 1:
        Matrix.translateM(mModel, 0, -mDistance, 0, 0); // Left.
        Matrix.rotateM(mModel, 0, 90, 0, 1f, 0);
        break;
    case 2:
        Matrix.translateM(mModel, 0, 0, 0, mDistance); // Behind.
        Matrix.rotateM(mModel, 0, 180, 0, 1f, 0);
        break;
    case 3:
        Matrix.translateM(mModel, 0, mDistance, 0, 0); // Right.
        Matrix.rotateM(mModel, 0, 270, 0, 1f, 0);
        break;
    }
}

From source file:com.github.matthesrieke.jprox.JProxViaParameterServlet.java

private void copyChannel(final ReadableByteChannel src, final WritableByteChannel dest) throws IOException {
    final ByteBuffer buffer = ByteBuffer.allocateDirect(16 * 1024);

    while (src.read(buffer) != -1) {
        buffer.flip();/*from  ww  w  .j  a va 2s .c  o m*/
        dest.write(buffer);
        buffer.compact();
    }

    buffer.flip();

    while (buffer.hasRemaining()) {
        dest.write(buffer);
    }
}

From source file:yui.classes.utils.IOUtils.java

public static byte[] fileReadNIO(String name) {
    FileInputStream f = null;//  www  .  j  av  a  2  s.  c  o  m
    ByteBuffer bb = null;
    try {
        f = new FileInputStream(name);

        FileChannel ch = f.getChannel();
        bb = ByteBuffer.allocateDirect(1024);

        long checkSum = 0L;
        int nRead;
        while ((nRead = ch.read(bb)) != -1) {
            bb.position(0);
            bb.limit(nRead);
            while (bb.hasRemaining()) {
                checkSum += bb.get();
            }
            bb.clear();
        }
    } catch (FileNotFoundException ex) {
        logger.error(ex.getMessage());
    } catch (IOException ex) {
        logger.error(ex.getMessage());
    } finally {
        try {
            f.close();
        } catch (IOException ex) {
            logger.error(ex.getMessage());
        }
    }
    return bb.array();

}

From source file:org.apache.hadoop.util.Crc32PerformanceTest.java

private ByteBuffer allocateByteBuffer(int length) {
    return direct ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length);
}

From source file:com.google.android.apps.body.LayersLoader.java

private void createColorBuffer(DrawGroup drawGroup) {
    int numVertices = drawGroup.vertexBufferData.capacity() / 8; // 3 pos, 3 norm, 2 texcoord

    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(numVertices * 2);
    byteBuffer.order(ByteOrder.nativeOrder());
    drawGroup.colorBufferData = byteBuffer.asShortBuffer();

    for (Draw draw : drawGroup.draws) {
        short selectionColor = mMaxColorIndex++;
        mSelectionColorMap.put((int) selectionColor, draw);

        BodyJni.setColorForIndices(drawGroup.colorBufferData, selectionColor, drawGroup.indexBufferData,
                draw.offset, draw.count);
    }//www .j  ava  2s .  c o  m
}

From source file:com.gpl_compression.lzo.LzoDecompressor.java

/**
 * Creates a new lzo decompressor.//from   w w  w  .j  a  v a 2 s . co m
 * 
 * @param strategy lzo decompression algorithm
 * @param directBufferSize size of the direct-buffer
 */
public LzoDecompressor(CompressionStrategy strategy, int directBufferSize) {
    this.directBufferSize = directBufferSize;
    this.strategy = strategy;

    compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
    uncompressedDirectBuf.position(directBufferSize);

    /**
     * Initialize {@link #lzoDecompress}
     */
    init(this.strategy.getDecompressor());
}

From source file:com.github.srgg.yads.impl.context.communication.AbstractTransport.java

private ByteBuffer encode(final byte msgCode, final byte[] payload) throws Exception {
    final int length = payload.length + 1;
    final ByteBuffer b = ByteBuffer.allocateDirect(length + 4 /* sizeof(length header) */).putInt(length)
            .put(msgCode).put(payload);/*  w  w w . j ava  2s  .c  o m*/

    assert b.remaining() == 0;
    b.flip();
    return b;
}

From source file:com.google.android.apps.body.LayersLoader.java

private static ShortBuffer decodeIndexBuffer(DrawGroup drawGroup, char[] data, int start, int length) {
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(length * 2);
    byteBuffer.order(ByteOrder.nativeOrder());
    ShortBuffer indexData = byteBuffer.asShortBuffer();
    int prev = 0;
    for (int i = 0; i < length;) {
        int limit = Math.min(length - i, BUFSIZE);
        int s = start + i;
        for (int j = 0; j < limit; ++j) {
            int word = data[s + j];
            prev += (word >> 1) ^ (-(word & 1));
            mBuffer[j] = (short) prev;
        }/*  w w w. j a va 2s  .c om*/
        i += limit;
        indexData.put(mBuffer, 0, limit);
    }
    indexData.rewind();
    return indexData;
}