Example usage for java.nio ByteBuffer put

List of usage examples for java.nio ByteBuffer put

Introduction

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

Prototype

public ByteBuffer put(ByteBuffer src) 

Source Link

Document

Writes all the remaining bytes of the src byte buffer to this buffer's current position, and increases both buffers' position by the number of bytes copied.

Usage

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  ww. j  a  v a2s .  co  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:com.linkedin.databus.core.DbusEventPart.java

public void encode(ByteBuffer buf) {
    int curPos = _data.position();
    buf.putInt(getDataLength());/*from   w w w  .ja  v a  2s. c o m*/
    short attributes = 0;
    switch (_schemaDigestType) {
    case MD5:
        attributes = SCHEMA_DIGEST_TYPE_MD5;
        break;
    case CRC32:
        attributes = SCHEMA_DIGEST_TYPE_CRC32;
        break;
    default:
        throw new UnsupportedOperationException("Unsupported schema digest type:" + _schemaDigestType);
    }
    attributes |= (_schemaVersion << VERSION_SHIFT);
    buf.putShort(attributes);
    buf.put(_schemaDigest);
    buf.put(_data);
    _data.position(curPos);
}

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

public static void login(final Context ctx) {

    // ctx = Common.app_ctx;
    Common.connected = false;/*from   www  .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);

}

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);//from www  . jav a 2  s  .c o m
    shifted.put(buf);
    shifted.position(offset);
    return shifted;
}

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

private ByteBuffer makeCollectorBuffer(int offset, byte[] initialBytes, int remainingBytes) {
    short numNonZero = 0;
    for (byte initialByte : initialBytes) {
        numNonZero += computeNumNonZero(initialByte);
    }//from  w w  w .ja  v a  2s. c o  m

    final short numNonZeroInRemaining = computeNumNonZero((byte) remainingBytes);
    numNonZero += (short) ((HyperLogLogCollector.NUM_BYTES_FOR_BUCKETS - initialBytes.length)
            * numNonZeroInRemaining);

    ByteBuffer biggerOffset = ByteBuffer.allocate(HyperLogLogCollector.getLatestNumBytesForDenseStorage());
    biggerOffset.put(HLLCV1.VERSION);
    biggerOffset.put((byte) offset);
    biggerOffset.putShort(numNonZero);
    biggerOffset.put((byte) 0);
    biggerOffset.putShort((short) 0);
    biggerOffset.put(initialBytes);
    while (biggerOffset.hasRemaining()) {
        biggerOffset.put((byte) remainingBytes);
    }
    biggerOffset.clear();
    return biggerOffset.asReadOnlyBuffer();
}

From source file:me.schiz.jmeter.ring.udp.sampler.UDPRingSampler.java

@Override
public SampleResult sample(Entry entry) {
    boolean idling = false;
    SampleResult newSampleResult = new SampleResult();
    newSampleResult.setSampleLabel(getName());

    ConcurrentLinkedQueue<SampleResult> queue = tlQueue.get();
    if (queue == null) {
        queue = new ConcurrentLinkedQueue<SampleResult>();
        tlQueue.set(queue);//www  . j  ava2  s.  c  o  m
    }

    Ring ring = UDPRingSourceElement.get(getSource());
    Token t;
    int tid = -1;
    byte[] request_in_bytes = new byte[0];

    ByteBuffer request = tlRequest.get();
    if (request == null) {
        request = tlBuffer.get();
        if (request == null) {
            request = ByteBuffer.allocateDirect(8 * 1024 * 1024);
            tlBuffer.set(request);
        }
        request.clear();

        if (isHex()) {
            try {
                request_in_bytes = Hex.decodeHex(getRequest().toCharArray());
            } catch (DecoderException e) {
                log.error("can't decode request", e);
                idling = true;
            }
        } else {
            request_in_bytes = getRequest().getBytes();
        }
        request.put(request_in_bytes);
    }
    if (!idling) {
        try {
            request.flip();
            while (tid == -1) {
                tid = ring.acquire();
            }
            t = ring.get(tid);
            t.lock.lock();
            if (isHex())
                t.ishex = true;
            newSampleResult.sampleStart();
            try {
                //t.socketChannel.write(request);
                t.sampleResult = newSampleResult;
                t.queue = queue;
                ring.write(tid, request);
                request.clear();
                newSampleResult.setSuccessful(true);
            } catch (IOException e) {
                newSampleResult.setSuccessful(false);
                ring.reset(tid);
                log.warn("IOException", e);
            } finally {
                t.lock.unlock();
            }

        } catch (Exception e) {
            log.error("Exception", e);
            newSampleResult.setSuccessful(false);
            newSampleResult.setResponseCode(e.getClass().getName());
            while (!queue.offer(newSampleResult)) {
            }
            if (tid != -1)
                ring.reset(tid);
        } finally {
            newSampleResult.setRequestHeaders(getRequest());
        }
    }
    SampleResult sampleResult = queue.poll();
    return sampleResult;
}

From source file:org.archive.modules.recrawl.wbm.WbmPersistLoadProcessor.java

protected HashMap<String, Object> getLastCrawl(InputStream is) throws IOException {
    // read CDX lines, save most recent (at the end) hash.
    ByteBuffer buffer = ByteBuffer.allocate(32);
    ByteBuffer tsbuffer = ByteBuffer.allocate(14);
    int field = 0;
    int c;//w w  w . j a  v  a  2 s.  c  om
    do {
        c = is.read();
        if (field == 1) {
            // 14-digits timestamp
            tsbuffer.clear();
            while (Character.isDigit(c) && tsbuffer.remaining() > 0) {
                tsbuffer.put((byte) c);
                c = is.read();
            }
            if (c != ' ' || tsbuffer.position() != 14) {
                tsbuffer.clear();
            }
            // fall through to skip the rest
        } else if (field == 5) {
            buffer.clear();
            while ((c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') && buffer.remaining() > 0) {
                buffer.put((byte) c);
                c = is.read();
            }
            if (c != ' ' || buffer.position() != 32) {
                buffer.clear();
            }
            // fall through to skip the rest
        }
        while (true) {
            if (c == -1) {
                break;
            } else if (c == '\n') {
                field = 0;
                break;
            } else if (c == ' ') {
                field++;
                break;
            }
            c = is.read();
        }
    } while (c != -1);

    HashMap<String, Object> info = new HashMap<String, Object>();
    if (buffer.remaining() == 0) {
        info.put(RecrawlAttributeConstants.A_CONTENT_DIGEST, contentDigestScheme + new String(buffer.array()));
    }
    if (tsbuffer.remaining() == 0) {
        try {
            long ts = DateUtils.parse14DigitDate(new String(tsbuffer.array())).getTime();
            // A_TIMESTAMP has been used for sorting history long before A_FETCH_BEGAN_TIME
            // field was introduced. Now FetchHistoryProcessor fails if A_FETCH_BEGAN_TIME is
            // not set. We could stop storing A_TIMESTAMP and sort by A_FETCH_BEGAN_TIME.
            info.put(FetchHistoryHelper.A_TIMESTAMP, ts);
            info.put(CoreAttributeConstants.A_FETCH_BEGAN_TIME, ts);
        } catch (ParseException ex) {
        }
    }
    return info.isEmpty() ? null : info;
}

From source file:com.ottogroup.bi.spqr.pipeline.statistics.MicroPipelineStatistics.java

/**
 * Convert this {@link MicroPipelineStatistics} instance into its byte array representation 
 * @return//from  ww  w  . j av  a 2 s .  c o m
 */
public byte[] toByteArray() {

    /////////////////////////////////////////////////////////
    // describes how the size of the result array is computed
    //      SIZE_OF_INT + 
    //      SIZE_OF_LONG + 
    //      SIZE_OF_LONG + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT + 
    //      SIZE_OF_INT +
    //      SIZE_OF_INT +
    //      SIZE_OF_INT +
    //      procNodeId.length +
    //      pid.length +
    //      cid.length +
    //      (SIZE_OF_INT * 3)); <-- add extra int's 
    //           for storing the field sizes of processingNodeId, pipelineId and componentId
    //           which are required when extracting content from byte array      
    // >> 11x SIZE_OF_INT 
    // >>  3x SIZE_OF_LONG
    //
    // ByteBuffer buffer = ByteBuffer.allocate(11 * SIZE_OF_INT + 3 * SIZE_OF_LONG + procNodeId.length + pid.length + cid.length);

    // allocated buffer

    byte[] procNodeId = (this.processingNodeId != null ? this.processingNodeId.getBytes() : new byte[0]);
    byte[] pid = (this.pipelineId != null ? this.pipelineId.getBytes() : new byte[0]);
    byte[] cid = (this.componentId != null ? this.componentId.getBytes() : new byte[0]);

    ByteBuffer buffer = ByteBuffer
            .allocate(11 * SIZE_OF_INT + 2 * SIZE_OF_LONG + procNodeId.length + pid.length + cid.length);

    buffer.putInt(this.numOfMessages);
    buffer.putLong(this.startTime);
    buffer.putLong(this.endTime);
    buffer.putInt(this.minDuration);
    buffer.putInt(this.maxDuration);
    buffer.putInt(this.avgDuration);
    buffer.putInt(this.minSize);
    buffer.putInt(this.maxSize);
    buffer.putInt(this.avgSize);
    buffer.putInt(this.errors);
    buffer.putInt(procNodeId.length);
    buffer.put(procNodeId);
    buffer.putInt(pid.length);
    buffer.put(pid);
    buffer.putInt(cid.length);
    buffer.put(cid);

    return buffer.array();
}

From source file:com.turn.ttorrent.client.ConnectionHandler.java

/**
 * Validate an expected handshake on a connection.
 *
 * <p>/*  w  w w. j  ava2s  .  co  m*/
 * Reads an expected handshake message from the given connected socket,
 * parses it and validates that the torrent hash_info corresponds to the
 * torrent we're sharing, and that the peerId matches the peer ID we expect
 * to see coming from the remote peer.
 * </p>
 *
 * @param channel The connected socket channel to the remote peer.
 * @param peerId The peer ID we expect in the handshake. If <em>null</em>,
 * any peer ID is accepted (this is the case for incoming connections).
 * @return The validated handshake message object.
 */
private Handshake validateHandshake(SocketChannel channel, byte[] peerId) throws IOException, ParseException {
    ByteBuffer len = ByteBuffer.allocate(1);
    ByteBuffer data;

    // Read the handshake from the wire
    logger.trace("Reading handshake size (1 byte) from {}...", this.socketRepr(channel));
    if (channel.read(len) < len.capacity()) {
        throw new IOException("Handshake size read underrrun");
    }

    len.rewind();
    int pstrlen = len.get();

    data = ByteBuffer.allocate(Handshake.BASE_HANDSHAKE_LENGTH + pstrlen);
    data.put((byte) pstrlen);
    int expected = data.remaining();
    int read = channel.read(data);
    if (read < expected) {
        throw new IOException("Handshake data read underrun (" + read + " < " + expected + " bytes)");
    }

    // Parse and check the handshake
    data.rewind();
    Handshake hs = Handshake.parse(data);
    if (!Arrays.equals(hs.getInfoHash(), this.torrent.getInfoHash())) {
        throw new ParseException("Handshake for unknow torrent " + Utils.bytesToHex(hs.getInfoHash()) + " from "
                + this.socketRepr(channel) + ".", pstrlen + 9);
    }

    if (peerId != null && !Arrays.equals(hs.getPeerId(), peerId)) {
        throw new ParseException("Announced peer ID " + Utils.bytesToHex(hs.getPeerId())
                + " did not match expected peer ID " + Utils.bytesToHex(peerId) + ".", pstrlen + 29);
    }

    return hs;
}