Example usage for java.nio ByteBuffer putInt

List of usage examples for java.nio ByteBuffer putInt

Introduction

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

Prototype

public abstract ByteBuffer putInt(int value);

Source Link

Document

Writes the given int to the current position and increases the position by 4.

Usage

From source file:edu.umass.cs.gigapaxos.paxospackets.PaxosPacket.java

protected ByteBuffer toBytes(ByteBuffer bbuf) throws UnsupportedEncodingException {
    // paxospacket stuff
    bbuf.putInt(PaxosPacket.PaxosPacketType.PAXOS_PACKET.getInt()); // type
    bbuf.putInt(this.packetType.getInt()); // paxos type
    bbuf.putInt(this.version);
    // paxosID length followed by paxosID
    byte[] paxosIDBytes = this.paxosID != null ? this.paxosID.getBytes(CHARSET) : new byte[0];
    bbuf.put((byte) paxosIDBytes.length);
    bbuf.put(paxosIDBytes);/*w  ww. j  ava2s.  c o  m*/
    assert (bbuf.position() == SIZEOF_PAXOSPACKET_FIXED + paxosIDBytes.length) : bbuf.position() + " != "
            + SIZEOF_PAXOSPACKET_FIXED + paxosIDBytes.length;
    return bbuf;
}

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 .java 2  s  .c om

    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:hivemall.mf.OnlineMatrixFactorizationUDTF.java

protected void beforeTrain(final long rowNum, final int user, final int item, final double rating)
        throws HiveException {
    if (inputBuf != null) {
        assert (fileIO != null);
        final ByteBuffer buf = inputBuf;
        int remain = buf.remaining();
        if (remain < RECORD_BYTES) {
            writeBuffer(buf, fileIO, lastWritePos);
            this.lastWritePos = rowNum;
        }//w w w. ja v a2 s.  c o m
        buf.putInt(user);
        buf.putInt(item);
        buf.putDouble(rating);
    }
}

From source file:org.apache.hadoop.hbase.ipc.AsyncRpcChannelImpl.java

private byte[] getChannelHeaderBytes(AuthMethod authMethod) {
    RPCProtos.ConnectionHeader header = getChannelHeader(authMethod);
    ByteBuffer b = ByteBuffer.allocate(header.getSerializedSize() + 4);
    b.putInt(header.getSerializedSize());
    b.put(header.toByteArray());//from   w  w  w .  j av a2  s. c  om
    return b.array();
}

From source file:org.apache.bookkeeper.bookie.BookieJournalTest.java

/**
 * Generate meta entry with given master key
 *//*  w  ww  . j  a v  a 2 s.  c om*/
private ByteBuffer generateMetaEntry(long ledgerId, byte[] masterKey) {
    ByteBuffer bb = ByteBuffer.allocate(8 + 8 + 4 + masterKey.length);
    bb.putLong(ledgerId);
    bb.putLong(Bookie.METAENTRY_ID_LEDGER_KEY);
    bb.putInt(masterKey.length);
    bb.put(masterKey);
    bb.flip();
    return bb;
}

From source file:hivemall.mf.BPRMatrixFactorizationUDTF.java

protected void beforeTrain(final long rowNum, final int u, final int i, final int j) throws HiveException {
    if (inputBuf != null) {
        assert (fileIO != null);
        final ByteBuffer buf = inputBuf;
        int remain = buf.remaining();
        if (remain < RECORD_BYTES) {
            writeBuffer(buf, fileIO, lastWritePos);
            this.lastWritePos = rowNum;
        }//from   w ww  .  j a  va  2 s .  co m
        buf.putInt(u);
        buf.putInt(i);
        buf.putInt(j);
    }
}

From source file:de.tum.frm2.nicos_android.nicos.NicosClient.java

public void _write(String command, Object args) throws IOException {
    // Write a command to the server
    // Format: ENQ + commandcode + length + payload
    Pickler pickler = new Pickler();
    byte[] data = pickler.dumps(args);

    ByteArrayOutputStream buffer = new ByteArrayOutputStream();
    buffer.write(daemon.ENQ);/*from  w w  w  . ja  va2 s .  co  m*/
    // frame format requires: length of (ENQ + commandcode) == 3 bytes
    // That's why an empty byte gets inserted here.
    buffer.write((byte) 0x00);
    buffer.write(daemon.command2code(command));
    ByteBuffer bb = ByteBuffer.allocate(4);
    bb.order(ByteOrder.BIG_ENDIAN);
    bb.putInt(data.length);
    buffer.write(bb.array());
    buffer.write(data);
    socketOut.write(buffer.toByteArray());
    socketOut.flush();
}

From source file:eu.stratosphere.nephele.services.iomanager.IOManagerPerformanceBenchmark.java

@SuppressWarnings("resource")
private final void speedTestNIO(int bufferSize, boolean direct) throws IOException {
    final Channel.ID tmpChannel = ioManager.createChannel();

    File tempFile = null;/*w  w  w.j  a va 2 s  .  c om*/
    FileChannel fs = null;

    try {
        tempFile = new File(tmpChannel.getPath());

        RandomAccessFile raf = new RandomAccessFile(tempFile, "rw");
        fs = raf.getChannel();

        ByteBuffer buf = direct ? ByteBuffer.allocateDirect(bufferSize) : ByteBuffer.allocate(bufferSize);

        long writeStart = System.currentTimeMillis();

        int valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.flip();
                fs.write(buf);
                buf.clear();
            }
            buf.putInt(valsLeft);
        }

        if (buf.position() > 0) {
            buf.flip();
            fs.write(buf);
        }

        fs.close();
        raf.close();
        fs = null;

        long writeElapsed = System.currentTimeMillis() - writeStart;

        // ----------------------------------------------------------------

        raf = new RandomAccessFile(tempFile, "r");
        fs = raf.getChannel();
        buf.clear();

        long readStart = System.currentTimeMillis();

        fs.read(buf);
        buf.flip();

        valsLeft = NUM_INTS_WRITTEN;
        while (valsLeft-- > 0) {
            if (buf.remaining() < 4) {
                buf.compact();
                fs.read(buf);
                buf.flip();
            }
            if (buf.getInt() != valsLeft) {
                throw new IOException();
            }
        }

        fs.close();
        raf.close();

        long readElapsed = System.currentTimeMillis() - readStart;

        LOG.info("NIO Channel with buffer " + bufferSize + ": write " + writeElapsed + " msecs, read "
                + readElapsed + " msecs.");
    } finally {
        // close if possible
        if (fs != null) {
            fs.close();
            fs = null;
        }
        // try to delete the file
        if (tempFile != null) {
            tempFile.delete();
        }
    }
}

From source file:it.anyplace.sync.bep.BlockExchangeConnectionHandler.java

private Future sendHelloMessage(final byte[] payload) {
    return outExecutorService.submit(new Runnable() {
        @Override// w  w  w. j av a 2 s. c o  m
        public void run() {
            try {
                logger.trace("sending message");
                ByteBuffer header = ByteBuffer.allocate(6);
                header.putInt(MAGIC);
                header.putShort((short) payload.length);
                out.write(header.array());
                out.write(payload);
                out.flush();
                logger.trace("sent message");
            } catch (IOException ex) {
                if (outExecutorService.isShutdown()) {
                    return;
                }
                logger.error("error writing to output stream", ex);
                closeBg();
            }
        }
    });
}

From source file:io.github.dsheirer.source.tuner.hackrf.HackRFTunerController.java

@Override
public void setTunedFrequency(long frequency) throws SourceException {
    ByteBuffer buffer = ByteBuffer.allocateDirect(8);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    int mhz = (int) (frequency / 1E6);
    int hz = (int) (frequency - (mhz * 1E6));

    buffer.putInt(mhz);
    buffer.putInt(hz);//from   w  w  w.  j a v  a2s. c om

    buffer.rewind();

    try {
        write(Request.SET_FREQUENCY, 0, 0, buffer);
    } catch (UsbException e) {
        mLog.error("error setting frequency [" + frequency + "]", e);

        throw new SourceException("error setting frequency [" + frequency + "]", e);
    }
}