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.mellanox.hadoop.mapred.UdaPlugin.java

public void dataFromUda(Object directBufAsObj, int len) throws Throwable {
    if (LOG.isDebugEnabled())
        LOG.debug("-->> dataFromUda len=" + len);

    KVBuf buf = kv_bufs[__cur_kv_idx__];

    synchronized (buf) {
        while (buf.status != kv_buf_recv_ready) {
            try {
                buf.wait();//from   w  w w. ja  v a2s. c o m
            } catch (InterruptedException e) {
            }
        }

        buf.act_len = len; // set merged size
        try {
            java.nio.ByteBuffer directBuf = (java.nio.ByteBuffer) directBufAsObj;
            directBuf.position(0); // reset read position         
            directBuf.get(buf.kv_buf, 0, len);// memcpy from direct buf into java buf - TODO: try zero-copy
        } catch (Throwable t) {
            LOG.error("!!! !! dataFromUda GOT Exception");
            LOG.error(StringUtils.stringifyException(t));
            throw (t);
        }

        buf.kv.reset(buf.kv_buf, 0, len); // reset KV read position

        buf.status = kv_buf_redc_ready;
        ++__cur_kv_idx__;
        if (__cur_kv_idx__ >= kv_buf_num) {
            __cur_kv_idx__ = 0;
        }
        buf.notifyAll();
    }
    if (LOG.isDebugEnabled())
        LOG.debug("<<-- dataFromUda finished callback");
}

From source file:io.github.dsheirer.record.wave.WaveWriter.java

/**
 * Writes the metadata to the end of the file if there is sufficient space without exceeding the
 * max file size./*w w w . j  a  v a 2 s.  c  om*/
 */
public void writeMetadata(WaveMetadata metadata) throws IOException {
    ByteBuffer listChunk = metadata.getLISTChunk();

    if (mFileChannel.size() + listChunk.capacity() >= mMaxSize) {
        throw new IOException("Cannot write LIST metadata chunk - insufficient file space remaining");
    }

    closeDataChunk();

    listChunk.position(0);

    while (listChunk.hasRemaining()) {
        mFileChannel.write(listChunk);
    }

    updateTotalSize();

    ByteBuffer id3Chunk = metadata.getID3Chunk();

    if (mFileChannel.size() + id3Chunk.capacity() >= mMaxSize) {
        throw new IOException("Cannot write ID3 metadata chunk - insufficient file space remaining");
    }

    id3Chunk.position(0);

    while (id3Chunk.hasRemaining()) {
        mFileChannel.write(id3Chunk);
    }

    updateTotalSize();
}

From source file:io.Text.java

/**
 * Finds any occurence of <code>what</code> in the backing
 * buffer, starting as position <code>start</code>. The starting
 * position is measured in bytes and the return value is in
 * terms of byte position in the buffer. The backing buffer is
 * not converted to a string for this operation.
 * @return byte position of the first occurence of the search
 *         string in the UTF-8 buffer or -1 if not found
 *//*w  ww.  j  av a2  s  .com*/
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found)
                    return pos;
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:org.apache.arrow.vector.util.Text.java

/**
 * Finds any occurence of <code>what</code> in the backing buffer, starting as position <code>start</code>. The
 * starting position is measured in bytes and the return value is in terms of byte position in the buffer. The backing
 * buffer is not converted to a string for this operation.
 *
 * @return byte position of the first occurence of the search string in the UTF-8 buffer or -1 if not found
 *//*  w w  w . j a  va  2s  .  c  o m*/
public int find(String what, int start) {
    try {
        ByteBuffer src = ByteBuffer.wrap(this.bytes, 0, this.length);
        ByteBuffer tgt = encode(what);
        byte b = tgt.get();
        src.position(start);

        while (src.hasRemaining()) {
            if (b == src.get()) { // matching first byte
                src.mark(); // save position in loop
                tgt.mark(); // save position in target
                boolean found = true;
                int pos = src.position() - 1;
                while (tgt.hasRemaining()) {
                    if (!src.hasRemaining()) { // src expired first
                        tgt.reset();
                        src.reset();
                        found = false;
                        break;
                    }
                    if (!(tgt.get() == src.get())) {
                        tgt.reset();
                        src.reset();
                        found = false;
                        break; // no match
                    }
                }
                if (found) {
                    return pos;
                }
            }
        }
        return -1; // not found
    } catch (CharacterCodingException e) {
        // can't get here
        e.printStackTrace();
        return -1;
    }
}

From source file:com.woodcomputing.bobbin.format.JEFFormat.java

@Override
public Design load(File file) {

    byte[] bytes = null;
    try (InputStream is = new FileInputStream(file)) {
        bytes = IOUtils.toByteArray(is);
    } catch (IOException ex) {
        log.catching(ex);//from  ww  w  .  j a v a  2s  .c  o m
    }
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    JEF jef = new JEF();
    jef.setFirstStitchLocation(bb.getInt(0));
    log.debug("First Stitch Location: {}", jef.getFirstStitchLocation());
    jef.setThreadChangeCount(bb.getInt(24));
    log.debug("Threads Changes: {}", jef.getThreadChangeCount());
    jef.setHoop(Hoop.id2Hoop(bb.getInt(32)));
    log.debug("Hoop: {}", jef.getHoop());
    jef.setStitchCount(bb.getInt(28));
    log.debug("Stitch Count: {}", jef.getStitchCount());

    bb.position(116);
    JEFColor[] colors = new JEFColor[jef.getThreadChangeCount()];
    for (int i = 0; i < jef.getThreadChangeCount(); i++) {
        colors[i] = jefColorMap.get(bb.getInt());
    }
    jef.setThreadColors(colors);
    for (int i = 0; i < jef.getThreadChangeCount(); i++) {
        log.debug("ThreadType{}: {}", i, bb.getInt());
    }

    int dx = 0;
    int dy = 0;
    int cx = 0;
    int cy = 0;
    int nx = 0;
    int ny = 0;

    int change = 1;
    int stitches = 0;
    boolean isMove = false;
    bb.position(jef.getFirstStitchLocation());
    JEFColor color = jef.getThreadColors()[change - 1];
    Design design = new Design();
    StitchGroup stitchGroup = new StitchGroup();
    stitchGroup.setColor(color.getRgb());

    for (int stitch = 1; stitch < jef.getStitchCount(); stitch++) {
        dx = bb.get();
        dy = bb.get();
        if (dx == -128) {
            switch (dy) {
            case 1:
                log.debug("change: {}", bb.position());
                change++;
                color = jef.getThreadColors()[change - 1];
                design.getStitchGroups().add(stitchGroup);
                stitchGroup = new StitchGroup();
                stitchGroup.setColor(color.getRgb());
                //                        bb.get();
                //                        bb.get();
                continue;
            case 2:
                //                        log.debug("move");
                isMove = true;
                break;
            case 16:
                log.debug("last");
                isMove = true;
                break;
            }
        } else {
            nx = cx + dx;
            ny = cy + dy;
            if (isMove) {
                isMove = false;
            }
            //                } else {
            //                    log.debug("stitch");
            stitches++;
            Stitch designStitch = new Stitch(cx, -cy, nx, -ny);
            stitchGroup.getStitches().add(designStitch);
            //                }
            cx = nx;
            cy = ny;
        }
    }
    log.debug("Changes: {} Stitches {} End: {}", change, stitches, bb.position());
    return design;
}

From source file:io.pcp.parfait.dxm.PcpMmvWriter.java

private void writeValueWithLockPerMetric(PcpValueInfo info, Object value, TypeHandler rawHandler) {
    ByteBuffer perMetricByteBuffer = perMetricByteBuffers.get(info);
    synchronized (perMetricByteBuffer) {
        perMetricByteBuffer.position(0);
        rawHandler.putBytes(perMetricByteBuffer, value);
    }//from ww w  .  j  a  va 2  s  . c  o  m

}

From source file:com.android.camera2.its.ItsUtils.java

public static byte[] getDataFromImage(Image image) throws ItsException {
    int format = image.getFormat();
    int width = image.getWidth();
    int height = image.getHeight();
    byte[] data = null;

    // Read image data
    Plane[] planes = image.getPlanes();//  w  ww .j ava 2 s  .  com

    // Check image validity
    if (!checkAndroidImageFormat(image)) {
        throw new ItsException("Invalid image format passed to getDataFromImage: " + image.getFormat());
    }

    if (format == ImageFormat.JPEG) {
        // JPEG doesn't have pixelstride and rowstride, treat it as 1D buffer.
        ByteBuffer buffer = planes[0].getBuffer();
        data = new byte[buffer.capacity()];
        buffer.get(data);
        return data;
    } else if (format == ImageFormat.YUV_420_888 || format == ImageFormat.RAW_SENSOR
            || format == ImageFormat.RAW10) {
        int offset = 0;
        data = new byte[width * height * ImageFormat.getBitsPerPixel(format) / 8];
        byte[] rowData = new byte[planes[0].getRowStride()];
        for (int i = 0; i < planes.length; i++) {
            ByteBuffer buffer = planes[i].getBuffer();
            int rowStride = planes[i].getRowStride();
            int pixelStride = planes[i].getPixelStride();
            int bytesPerPixel = ImageFormat.getBitsPerPixel(format) / 8;
            Logt.i(TAG, String.format("Reading image: fmt %d, plane %d, w %d, h %d, rowStride %d, pixStride %d",
                    format, i, width, height, rowStride, pixelStride));
            // For multi-planar yuv images, assuming yuv420 with 2x2 chroma subsampling.
            int w = (i == 0) ? width : width / 2;
            int h = (i == 0) ? height : height / 2;
            for (int row = 0; row < h; row++) {
                if (pixelStride == bytesPerPixel) {
                    // Special case: optimized read of the entire row
                    int length = w * bytesPerPixel;
                    buffer.get(data, offset, length);
                    // Advance buffer the remainder of the row stride
                    buffer.position(buffer.position() + rowStride - length);
                    offset += length;
                } else {
                    // Generic case: should work for any pixelStride but slower.
                    // Use intermediate buffer to avoid read byte-by-byte from
                    // DirectByteBuffer, which is very bad for performance.
                    // Also need avoid access out of bound by only reading the available
                    // bytes in the bytebuffer.
                    int readSize = rowStride;
                    if (buffer.remaining() < readSize) {
                        readSize = buffer.remaining();
                    }
                    buffer.get(rowData, 0, readSize);
                    if (pixelStride >= 1) {
                        for (int col = 0; col < w; col++) {
                            data[offset++] = rowData[col * pixelStride];
                        }
                    } else {
                        // PixelStride of 0 can mean pixel isn't a multiple of 8 bits, for
                        // example with RAW10. Just copy the buffer, dropping any padding at
                        // the end of the row.
                        int length = (w * ImageFormat.getBitsPerPixel(format)) / 8;
                        System.arraycopy(rowData, 0, data, offset, length);
                        offset += length;
                    }
                }
            }
        }
        Logt.i(TAG, String.format("Done reading image, format %d", format));
        return data;
    } else {
        throw new ItsException("Unsupported image format: " + format);
    }
}

From source file:com.woodcomputing.bobbin.format.PESFormat.java

@Override
public Design load(File file) {

    byte[] bytes = null;
    try (InputStream is = new FileInputStream(file)) {
        bytes = IOUtils.toByteArray(is);
    } catch (IOException ex) {
        log.catching(ex);/*from w  ww.ja  v a  2 s. c om*/
    }
    ByteBuffer bb = ByteBuffer.wrap(bytes);
    bb.order(ByteOrder.LITTLE_ENDIAN);
    Design design = new Design();
    log.debug("Magic: {}{}{}{}", (char) bb.get(), (char) bb.get(), (char) bb.get(), (char) bb.get());
    int pecStart = bb.getInt(8);
    log.debug("PEC Start: {}", pecStart);
    byte colorCount = bb.get(pecStart + 48);
    log.debug("Color Count: {}", colorCount);
    int colors[] = new int[colorCount];
    for (int i = 0; i < colorCount; i++) {
        colors[i] = bb.get() & 0xFF;
        log.debug("Color[{}] = {}", i, colors[i]);
    }

    bb.position(pecStart + 532);
    int x;
    int y;
    int colorChanges = 0;
    PESColor color = pesColorMap.get(colors[colorChanges++]);
    StitchGroup stitchGroup = new StitchGroup();
    stitchGroup.setColor(color.getColor());

    while (true) {
        x = bb.get() & 0xFF;
        y = bb.get() & 0xFF;
        if (x == 0xFF && y == 0x00) {
            log.debug("End of stitches");
            break;
        }
        if (x == 0xFE && y == 0xB0) {
            int colorIndex = bb.get() & 0xFF;
            log.debug("Color change: {}", colorIndex);
            color = pesColorMap.get(colors[colorChanges++]);
            stitchGroup = new StitchGroup();
            stitchGroup.setColor(color.getColor());
            continue;
        }
        if ((x & 0x80) > 0) {
            log.debug("Testing X: {} -  X & 0x80: {}", x, x & 0x80);
            if ((x & 0x20) > 0) {
                log.debug("Stich type TRIM");
            }
            if ((x & 0x10) > 0) {
                log.debug("Stich type JUMP");
            }
            x = ((x & 0x0F) << 8) + y;

            if ((x & 0x800) > 0) {
                x -= 0x1000;
            }
            y = bb.get() & 0xFF;

        } else if (x >= 0x40) {
            x -= 0x80;
        }
        if ((y & 0x80) > 0) {
            log.debug("Testing Y: {} -  Y & 0x80: {}", y, y & 0x80);
            if ((y & 0x20) > 0) {
                log.debug("Stich type TRIM");
            }
            if ((y & 0x10) > 0) {
                log.debug("Stich type JUMP");
            }
            y = ((y & 0x0F) << 8) + bb.get() & 0xFF;

            if ((y & 0x800) > 0) {
                y -= 0x1000;
            }
        } else if (y >= 0x40) {
            y -= 0x80;
        }
        //            Stitch designStitch = new Stitch(cx, -cy, nx, -ny);
        //            stitchGroup.getStitches().add(designStitch);
        log.debug("X: {} Y: {}", x, y);
    }
    log.debug("Color Changes: {}", colorChanges);
    return design;
}

From source file:io.druid.hll.HyperLogLogCollectorTest.java

protected ByteBuffer shiftedBuffer(ByteBuffer buf, int offset) {
    ByteBuffer shifted = ByteBuffer.allocate(buf.remaining() + offset);
    shifted.position(offset);
    shifted.put(buf);//from  w  w  w .ja v a  2s. c o m
    shifted.position(offset);
    return shifted;
}

From source file:com.vkassin.mtrade.Common.java

public static void login(final Context ctx) {

    // ctx = Common.app_ctx;
    Common.connected = false;//from   w w w. j  a  v a2 s .  c  o m

    if (inLogin)
        return;

    inLogin = true;

    if (Common.mainActivity != null)
        Common.mainActivity.handler.sendMessage(
                Message.obtain(Common.mainActivity.handler, Common.mainActivity.DISMISS_PROGRESS_DIALOG));

    // while(true) {

    final Dialog dialog = new Dialog(ctx);
    dialog.setContentView(R.layout.login_dialog);
    dialog.setTitle(R.string.LoginDialogTitle);
    dialog.setCancelable(false);

    final EditText nametxt = (EditText) dialog.findViewById(R.id.loginnameedit);
    final EditText passtxt = (EditText) dialog.findViewById(R.id.passwordedit);
    final EditText passtxt1 = (EditText) dialog.findViewById(R.id.passwordedit1);
    final EditText passtxt2 = (EditText) dialog.findViewById(R.id.passwordedit2);
    final EditText mailtxt = (EditText) dialog.findViewById(R.id.emailedit2);

    String nam = myaccount.get("name");
    Common.oldName = nam;

    if (nam != null) {

        nametxt.setText(nam);
        passtxt.requestFocus();
    }

    Button customDialog_Register = (Button) dialog.findViewById(R.id.goregister);
    customDialog_Register.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.setTitle(R.string.LoginDialogTitle1);
            final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
            layreg.setVisibility(View.VISIBLE);
            final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
            laylog.setVisibility(View.GONE);
        }

    });

    Button customDialog_Register1 = (Button) dialog.findViewById(R.id.goregister1);
    customDialog_Register1.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            if (mailtxt.getText().length() < 1) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectEmail, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();

                return;
            }

            if (passtxt1.getText().length() < 1) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
                return;
            }

            if (!passtxt2.getText().toString().equals(passtxt1.getText().toString())) {

                Toast toast = Toast.makeText(mainActivity, R.string.CorrectPassword1, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();
                return;
            }

            try {

                Socket sock = new Socket(ip_addr, port_register);

                JSONObject msg = new JSONObject();
                msg.put("objType", Common.MSG_REGISTER);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("user", mailtxt.getText().toString());
                msg.put("passwd", passtxt1.getText().toString());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("sign", sign(mailtxt.getText().toString(), passtxt1.getText().toString()));

                byte[] array = msg.toString().getBytes();
                ByteBuffer buff = ByteBuffer.allocate(array.length + 4);
                buff.putInt(array.length);
                buff.put(array);
                sock.getOutputStream().write(buff.array());

                ByteBuffer buff1 = ByteBuffer.allocate(4);
                buff1.put(readMsg(sock.getInputStream(), 4));
                buff1.position(0);
                int pkgSize = buff1.getInt();
                // Log.i(TAG, "size = "+pkgSize);
                String s = new String(readMsg(sock.getInputStream(), pkgSize));

                sock.close();

                JSONObject jo = new JSONObject(s);

                Log.i(TAG, "register answer = " + jo);

                int t = jo.getInt("status");
                switch (t) {

                case 1:
                    Toast toast = Toast.makeText(mainActivity, R.string.RegisterStatus1, Toast.LENGTH_LONG);
                    toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast.show();

                    dialog.setTitle(R.string.LoginDialogTitle);
                    final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
                    layreg.setVisibility(View.GONE);
                    final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
                    laylog.setVisibility(View.VISIBLE);

                    nametxt.setText(mailtxt.getText());
                    break;

                case -2:
                    Toast toast1 = Toast.makeText(mainActivity, R.string.RegisterStatus3, Toast.LENGTH_LONG);
                    toast1.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast1.show();
                    break;

                default:
                    Toast toast2 = Toast.makeText(mainActivity, R.string.RegisterStatus2, Toast.LENGTH_LONG);
                    toast2.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                    toast2.show();
                    break;

                }

            } catch (Exception e) {

                e.printStackTrace();
                Log.e(TAG, "Error in registration process!!", e);

                Toast toast = Toast.makeText(mainActivity, R.string.ConnectError, Toast.LENGTH_LONG);
                toast.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, 0);
                toast.show();

            }

        }

    });

    Button customDialog_CancelReg = (Button) dialog.findViewById(R.id.cancelreg);
    customDialog_CancelReg.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            dialog.setTitle(R.string.LoginDialogTitle);
            final LinearLayout layreg = (LinearLayout) dialog.findViewById(R.id.reglayout354);
            layreg.setVisibility(View.GONE);
            final LinearLayout laylog = (LinearLayout) dialog.findViewById(R.id.loginlayout543);
            laylog.setVisibility(View.VISIBLE);

        }

    });

    Button customDialog_Dismiss = (Button) dialog.findViewById(R.id.gologin);
    customDialog_Dismiss.setOnClickListener(new Button.OnClickListener() {
        public void onClick(View arg0) {

            final RadioButton bu0 = (RadioButton) dialog.findViewById(R.id.lradio0);
            Common.isSSL = bu0.isChecked();

            inLogin = false;

            JSONObject msg = new JSONObject();
            try {

                msg.put("objType", Common.LOGOUT);
                msg.put("time", Calendar.getInstance().getTimeInMillis());
                msg.put("version", Common.PROTOCOL_VERSION);
                msg.put("status", 1);
                mainActivity.writeJSONMsg(msg);
            } catch (Exception e) {
                e.printStackTrace();
                Log.e(TAG, "Error! Cannot create JSON logout object", e);
            }

            myaccount.put("name", nametxt.getText().toString());
            myaccount.put("password", passtxt.getText().toString());

            Log.i(TAG,
                    "myaccount username: " + myaccount.get("name") + " password: " + myaccount.get("password"));

            dialog.dismiss();
            mainActivity.stop();
            // saveAccountDetails();
            try {
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            loginFromDialog = true;
            //            mainActivity.refresh();

            Common.keypassword(ctx);
        }

    });

    dialog.show();
    // Common.confChanged = false;
    // }//while(true);

}