Example usage for java.nio ByteBuffer position

List of usage examples for java.nio ByteBuffer position

Introduction

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

Prototype

public final Buffer position(int newPosition) 

Source Link

Document

Sets the position of this buffer.

Usage

From source file:com.nridge.core.base.std.BufUtl.java

/**
 * Resets the <code>ByteBuffer</code> position and adds the opcode and
 * version values to it.// w  w w  .ja v  a  2s . c o m
 *
 * @param aBuffer Packet byte buffer object.
 * @param anOpCode Application specific operation code value.
 * @param aVersion Application specific operation version code value.
 */
public static void setHeader(ByteBuffer aBuffer, int anOpCode, int aVersion) {
    if (aBuffer != null) {
        aBuffer.mark();
        aBuffer.position(0);
        aBuffer.putInt(anOpCode);
        aBuffer.putInt(aVersion);
        aBuffer.reset();
    }
}

From source file:com.linkedin.databus.core.util.StringUtils.java

/**
 * Dumps as a hex string the contents of a buffer around a position
 * @param buf     the ByteBuffer to dump
 * @param bufOfs  starting offset in the buffer
 * @param length  the number of bytes to print
 * @return the hexstring/*from   w ww  .  jav  a 2s . co  m*/
 */
public static String hexdumpByteBufferContents(ByteBuffer buf, int bufOfs, int length) {
    if (length < 0) {
        return "";
    }

    final int endOfs = Math.min(buf.limit(), bufOfs + length + 1);
    final byte[] bytes = new byte[endOfs - bufOfs];

    buf = buf.duplicate();
    buf.position(bufOfs);
    buf.get(bytes);
    return new String(Hex.encodeHex(bytes));
}

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);/*w  w w  .  j  ava  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:com.nridge.core.base.std.BufUtl.java

/**
 * Retrieves the operation code stored within the header of the
 * <code>ByteBuffer</code> object.
 *
 * @param aBuffer Packet byte buffer object.
 * @return Application specific operation code value.
 *///from   ww  w. j a  v  a  2  s  . com
public static int getOpCode(ByteBuffer aBuffer) {
    int opCode;

    if (aBuffer == null)
        return -1;
    else {
        aBuffer.mark();
        aBuffer.position(0);
        opCode = aBuffer.getInt();
        aBuffer.reset();

        return opCode;
    }
}

From source file:com.nridge.core.base.std.BufUtl.java

/**
 * Retrieves the operation version code stored within the header of the
 * <code>ByteBuffer</code> object.
 *
 * @param aBuffer Packet byte buffer object.
 * @return Application specific operation code version value.
 *///ww  w  . j  a  v  a  2  s .c om
@SuppressWarnings({ "UnusedAssignment" })
public static int getVersion(ByteBuffer aBuffer) {
    int opCode, versionId;

    if (aBuffer == null)
        return -1;
    else {
        aBuffer.mark();
        aBuffer.position(0);
        opCode = aBuffer.getInt();
        versionId = aBuffer.getInt();
        aBuffer.reset();

        return versionId;
    }
}

From source file:net.pms.util.AudioUtils.java

private static void parseRealAudioMetaData(ByteBuffer buffer, DLNAMediaAudio audio, short version) {
    buffer.position(buffer.position() + (version == 4 ? 3 : 4)); // skip unknown
    byte b = buffer.get();
    if (b != 0) {
        byte[] title = new byte[Math.min(b & 0xFF, buffer.remaining())];
        buffer.get(title);/*  w  ww  .  ja  v  a2s .c o m*/
        String titleString = new String(title, StandardCharsets.US_ASCII);
        audio.setSongname(titleString);
        audio.setAudioTrackTitleFromMetadata(titleString);
    }
    if (buffer.hasRemaining()) {
        b = buffer.get();
        if (b != 0) {
            byte[] artist = new byte[Math.min(b & 0xFF, buffer.remaining())];
            buffer.get(artist);
            audio.setArtist(new String(artist, StandardCharsets.US_ASCII));
        }
    }
}

From source file:com.spectralogic.ds3client.utils.IOUtils.java

public static long copy(final InputStream inputStream, final WritableByteChannel writableByteChannel,
        final int bufferSize, final String objName, final boolean isPutCommand) throws IOException {
    final byte[] buffer = new byte[bufferSize];
    final ByteBuffer byteBuffer = ByteBuffer.wrap(buffer);
    int len;//from   ww w  .  ja  v  a 2 s  . c om
    long totalBytes = 0;

    final long startTime = PerformanceUtils.getCurrentTime();
    long statusUpdateTime = startTime;

    try {
        while ((len = inputStream.read(buffer)) != -1) {
            totalBytes += len;

            try {
                byteBuffer.position(0);
                byteBuffer.limit(len);
                writableByteChannel.write(byteBuffer);
            } catch (final Throwable t) {
                throw new UnrecoverableIOException(t);
            }

            final long curTime = PerformanceUtils.getCurrentTime();
            if (statusUpdateTime <= curTime) {
                PerformanceUtils.logMbpsStatus(startTime, curTime, totalBytes, objName, isPutCommand);
                statusUpdateTime += 60000D; //Only logs status once a minute
            }
        }
    } catch (final ConnectionClosedException e) {
        LOG.error("Connection closed trying to copy from stream to channel.", e);
    }

    return totalBytes;
}

From source file:Main.java

public static ByteBuffer cloneByteBuffer(final ByteBuffer original) {
    // Create clone with same capacity as original.
    final ByteBuffer clone = (original.isDirect()) ? ByteBuffer.allocateDirect(original.capacity())
            : ByteBuffer.allocate(original.capacity());

    // Create a read-only copy of the original.
    // This allows reading from the original without modifying it.
    final ByteBuffer readOnlyCopy = original.asReadOnlyBuffer();

    // Flip and read from the original.
    readOnlyCopy.flip();/*from w w  w .  j  a v a 2 s  .  c  om*/
    clone.put(readOnlyCopy);
    clone.position(original.position());
    clone.limit(original.limit());
    clone.order(original.order());
    return clone;
}

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;
    }/*ww  w .  j a va2  s  .co  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:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Creates a data chunk header with the chunk size initialized to zero
 *///from ww  w  .j  a v a2  s .c o m
public static ByteBuffer getDataHeader() {
    ByteBuffer header = ByteBuffer.allocate(8);
    header.put(DATA_CHUNK_ID.getBytes());
    header.position(0);

    return header;
}