Example usage for java.nio ByteBuffer putShort

List of usage examples for java.nio ByteBuffer putShort

Introduction

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

Prototype

public abstract ByteBuffer putShort(short value);

Source Link

Document

Writes the given short to the current position and increases the position by 2.

Usage

From source file:org.midonet.netlink.rtnetlink.Link.java

@Override
public int serializeInto(ByteBuffer buf) {
    int start = buf.position();
    buf.put(ifi.family);/*  w  w w. j ava 2 s .c o m*/
    buf.put((byte) 0);
    buf.putShort(ifi.type);
    buf.putInt(ifi.index);
    buf.putInt(ifi.flags);
    buf.putInt(ifi.change);

    if (ifname != null) {
        NetlinkMessage.writeStringAttr(buf, Attr.IFLA_IFNAME, ifname);
    }

    if (mac != null) {
        NetlinkMessage.writeRawAttribute(buf, Attr.IFLA_ADDRESS, mac.getAddress());
    }

    if (mtu > 0) {
        NetlinkMessage.writeIntAttr(buf, Attr.IFLA_MTU, mtu);
    }

    if (masterIndex != 0) {
        NetlinkMessage.writeIntAttr(buf, Attr.IFLA_MASTER, masterIndex);
    }

    if (operstate != OperStatus.IF_OPER_UNKNOWN) {
        NetlinkMessage.writeByteAttr(buf, Attr.IFLA_OPERSTATE, operstate);
    }

    NetlinkMessage.writeAttrNested(buf, Attr.IFLA_LINKINFO, info);

    return buf.position() - start;
}

From source file:voldemort.store.cachestore.impl.ChannelStore.java

public void writeIndexBlock(CacheBlock<byte[]> block, long keyOffset2Len, FileChannel channel)
        throws IOException {
    long pos = OFFSET + (long) block.getRecordNo() * RECORD_SIZE;
    checkFileSize(pos, RECORD_SIZE);//from w  w  w .j  a v  a  2 s.  c  o m
    ByteBuffer buf = ByteBuffer.allocate(RECORD_SIZE);
    buf.put(block.getStatus());
    buf.putLong(keyOffset2Len);
    buf.putLong(block.getDataOffset2Len());
    buf.putLong(block.getBlock2Version());
    buf.putShort(block.getNode());
    buf.flip();
    channel.write(buf, pos);
}

From source file:tor.TorCircuit.java

/**
 * Builds a relay cell payload (not including cell header, only relay header)
 *
 * @param toHop   Hop that it's destined for
 * @param cmd     Command ID, see RELAY_
 * @param stream  Stream ID/* w  w w .  j  av a2  s . c  o  m*/
 * @param payload Relay cell data
 * @return Constructed relay payload
 */
protected synchronized byte[] buildRelay(TorHop toHop, int cmd, short stream, byte[] payload) {
    byte[] fnl = new byte[509];
    ByteBuffer buf = ByteBuffer.wrap(fnl);
    buf.put((byte) cmd);
    buf.putShort((short) 0); // recognised
    buf.putShort(stream);
    buf.putInt(0); // digest

    if (payload != null) {
        buf.putShort((short) payload.length);
        buf.put(payload);
    } else {
        buf.putShort((short) 0);
    }

    toHop.df_md.update(fnl);
    MessageDigest md;
    try {
        md = (MessageDigest) toHop.df_md.clone();

        byte digest[] = md.digest();

        //byte [] fnl_final = new byte[509];
        System.arraycopy(digest, 0, fnl, 5, 4);

        return fnl;
    } catch (CloneNotSupportedException e) {
        throw new RuntimeException(e);
    }

}

From source file:org.opendaylight.controller.topology.web.Topology.java

/**
 * Add regular hosts to main topology//from w w w  . ja va2 s  .  c  o  m
 *
 * @param hostEdges - node-nodeconnectors host-specific mapping from topology
 * @param topology - topology instance
 */
private void addHostNodes(Map<Node, Set<NodeConnector>> hostEdges, ITopologyManager topology,
        String containerName) {
    for (Map.Entry<Node, Set<NodeConnector>> e : hostEdges.entrySet()) {
        for (NodeConnector connector : e.getValue()) {
            List<Host> hosts = topology.getHostsAttachedToNodeConnector(connector);
            for (Host host : hosts) {
                EthernetAddress dmac = (EthernetAddress) host.getDataLayerAddress();

                ByteBuffer addressByteBuffer = ByteBuffer.allocate(8);
                addressByteBuffer.putShort((short) 0);
                addressByteBuffer.put(dmac.getValue());
                addressByteBuffer.rewind();

                long hid = addressByteBuffer.getLong();
                String hostId = String.valueOf(hid);

                NodeBean hostBean = new NodeBean(hostId, host.getNetworkAddressAsString(), NodeType.HOST);
                List<Map<String, Object>> adjacencies = new LinkedList<Map<String, Object>>();
                EdgeBean edge = new EdgeBean(connector, hid);
                adjacencies.add(edge.out());
                hostBean.setLinks(adjacencies);

                if (metaCache.get(containerName).containsKey(hostId)) {
                    Map<String, Object> hostEntry = metaCache.get(containerName).get(hostId);
                    hostEntry.put("adjacencies", adjacencies);
                    stagedNodes.put(hostId, hostEntry);
                } else {
                    newNodes.put(String.valueOf(hid), hostBean.out());
                }
            }
        }
    }
}

From source file:tor.TorCircuit.java

/**
 * Sends an extend cell to extend the circuit to specified hop
 *
 * @param nextHop Hop to extend to/*from  w ww.j a  va  2s  .c o  m*/
 * @throws IOException
 */
public void extend(OnionRouter nextHop) throws IOException {
    if (state == STATES.DESTROYED) {
        log.error("Trying to use destroyed circuit");
        throw new RuntimeException("Trying to use destroyed circuit");
    }

    // Unused, throws ArrayIndexOutOfBoundsException when extend() is called after createCircuit()
    // without the fix to getLastHop() which returns null when hops.size() == 0
    //TorHop lastHop = getLastHop();

    byte create[] = createPayload(nextHop);
    byte extend[] = new byte[4 + 2 + create.length + TorCrypto.HASH_LEN];
    ByteBuffer buf = ByteBuffer.wrap(extend);
    buf.put(nextHop.ip.getAddress());
    buf.putShort((short) nextHop.orport);
    buf.put(create);
    buf.put(Hex.decode(nextHop.identityhash));

    send(extend, RELAY_EXTEND, true, (short) 0);
    //byte []payload = encrypt(buildRelay(lastHop, RELAY_EXTEND, (short)0, extend));
    //sock.sendCell(circId, Cell.RELAY_EARLY, payload);

    setState(STATES.EXTENDING);

    if (blocking)
        waitForState(STATES.READY, false);
}

From source file:oyagev.projects.android.ArduCopter.BluetoothChat.java

private void addControl(String name, String type, int commandValue) {

    Log.d(TAG, "Adding cmd: " + commandValue);

    LinearLayout row = new LinearLayout(this);
    row.setOrientation(LinearLayout.HORIZONTAL);
    row.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));

    View view = new TextView(this);

    //hidden view for command value
    TextView cmdView = new TextView(this);
    cmdView.setLayoutParams(new LinearLayout.LayoutParams(0, 0));
    cmdView.setVisibility(View.INVISIBLE);
    cmdView.setText(String.valueOf(commandValue));
    cmdView.setTag("cmd");

    //Setup the control
    if (type.equals("Button")) {
        view = new Button(this);

        ((Button) view).setText(name);
        ((Button) view).setOnClickListener(new OnClickListener() {

            @Override/*from   ww  w. ja  v a2s.  c o m*/
            public void onClick(View v) {
                TextView cmd = (TextView) ((LinearLayout) v.getParent()).findViewWithTag("cmd");

                dispatchUserEvent((int) Integer.valueOf(cmd.getText().toString()), new byte[] { 1 });

            }
        });
    } else if (type.equals("Edit")) {
        view = new EditText(this);

        ((EditText) view).setText(name);
    } else if (type.equals("Label")) {
        view = new TextView(this);

        ((TextView) view).setText(name);
    } else if (type.equals("Scrollbar")) {
        view = new LinearLayout(this);

        TextView text = new TextView(this);
        text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        text.setText(name);
        text.setTag("seek_text");
        SeekBar bar = new SeekBar(this);
        bar.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        ((LinearLayout) view).setOrientation(LinearLayout.VERTICAL);

        ((LinearLayout) view).addView(text);
        ((LinearLayout) view).addView(bar);

        bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {

                TextView cmd = (TextView) ((LinearLayout) ((LinearLayout) seekBar.getParent()).getParent())
                        .findViewWithTag("cmd");

                ByteBuffer buffer = ByteBuffer.allocate(2);
                buffer.putShort((short) progress);

                dispatchUserEvent((int) Integer.valueOf(cmd.getText().toString()), buffer.array());

            }
        });
    } else if (type.equals("Input String")) {
        view = new LinearLayout(this);

        TextView text = new TextView(this);
        text.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));
        text.setText(name);
        text.setTag("inp_text");
        TextView inp = new TextView(this);
        inp.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                LinearLayout.LayoutParams.WRAP_CONTENT));

        //((LinearLayout)view).setOrientation(LinearLayout.VERTICAL);

        ((LinearLayout) view).addView(text);
        ((LinearLayout) view).addView(inp);

        ycomm.registerCallback((byte) commandValue, new CallbackView(getApplicationContext(), inp) {
            @Override
            public void run(byte type, byte command, byte[] data, byte data_langth) {
                // TODO Auto-generated method stub
                String str = new String(data);
                ((TextView) this.view).setText(str);
            }
        });
    } else {
        return;
    }
    view.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT));

    row.addView(cmdView);
    row.addView(view);
    ((LinearLayout) findViewById(R.id.controls_layout)).addView(row);

}

From source file:org.opendaylight.lispflowmapping.lisp.serializer.MapNotifySerializer.java

public ByteBuffer serialize(MapNotify mapNotify) {
    int size = Length.HEADER_SIZE;
    if (mapNotify.getAuthenticationData() != null) {
        size += mapNotify.getAuthenticationData().length;
    }//from w  ww. jav  a 2 s.  c  o  m
    if (mapNotify.isXtrSiteIdPresent() != null && mapNotify.isXtrSiteIdPresent()) {
        size += org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer.Length.XTRID_SIZE
                + org.opendaylight.lispflowmapping.lisp.serializer.MapRegisterSerializer.Length.SITEID_SIZE;
    }
    for (MappingRecordItem mappingRecord : mapNotify.getMappingRecordItem()) {
        size += MappingRecordSerializer.getInstance().getSerializationSize(mappingRecord.getMappingRecord());
    }

    ByteBuffer replyBuffer = ByteBuffer.allocate(size);
    replyBuffer.put((byte) (MessageType.MapNotify.getIntValue() << 4));
    replyBuffer.position(replyBuffer.position() + Length.RES);
    replyBuffer.put(ByteUtil.boolToBit(BooleanUtils.isTrue(mapNotify.isMergeEnabled()), Flags.MERGE_ENABLED));
    if (mapNotify.getMappingRecordItem() != null) {
        replyBuffer.put((byte) mapNotify.getMappingRecordItem().size());
    } else {
        replyBuffer.put((byte) 0);
    }
    replyBuffer.putLong(NumberUtil.asLong(mapNotify.getNonce()));
    replyBuffer.putShort(NumberUtil.asShort(mapNotify.getKeyId()));
    if (mapNotify.getAuthenticationData() != null) {
        replyBuffer.putShort((short) mapNotify.getAuthenticationData().length);
        replyBuffer.put(mapNotify.getAuthenticationData());
    } else {
        replyBuffer.putShort((short) 0);
    }

    if (mapNotify.getMappingRecordItem() != null) {
        for (MappingRecordItem mappingRecord : mapNotify.getMappingRecordItem()) {
            MappingRecordSerializer.getInstance().serialize(replyBuffer, mappingRecord.getMappingRecord());
        }
    }

    if (mapNotify.isXtrSiteIdPresent() != null && mapNotify.isXtrSiteIdPresent()) {
        replyBuffer.put(mapNotify.getXtrId().getValue());
        replyBuffer.put(mapNotify.getSiteId().getValue());
    }
    replyBuffer.clear();
    return replyBuffer;
}

From source file:org.apache.carbondata.core.util.CarbonUtil.java

/**
 * This method will form one single byte [] for all the high card dims.
 * First it will add all the indexes of variable length byte[] and then the
 * actual value/*from  w  ww.j av  a2  s. c  om*/
 *
 * @param byteBufferArr
 * @return byte[] key.
 */
public static byte[] packByteBufferIntoSingleByteArray(ByteBuffer[] byteBufferArr) {
    // for empty array means there is no data to remove dictionary.
    if (null == byteBufferArr || byteBufferArr.length == 0) {
        return null;
    }
    int noOfCol = byteBufferArr.length;
    short offsetLen = (short) (noOfCol * 2);
    int totalBytes = calculateTotalBytes(byteBufferArr) + offsetLen;
    ByteBuffer buffer = ByteBuffer.allocate(totalBytes);
    // writing the offset of the first element.
    buffer.putShort(offsetLen);

    // prepare index for byte []
    for (int index = 0; index < byteBufferArr.length - 1; index++) {
        ByteBuffer individualCol = byteBufferArr[index];
        int noOfBytes = individualCol.capacity();
        buffer.putShort((short) (offsetLen + noOfBytes));
        offsetLen += noOfBytes;
        individualCol.rewind();
    }

    // put actual data.
    for (int index = 0; index < byteBufferArr.length; index++) {
        ByteBuffer individualCol = byteBufferArr[index];
        buffer.put(individualCol.array());
    }

    buffer.rewind();
    return buffer.array();

}

From source file:com.linkedin.databus.core.DbusEventPart.java

public void encode(ByteBuffer buf) {
    int curPos = _data.position();
    buf.putInt(getDataLength());/*from  ww w .  java2s . co 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:org.opendaylight.lispflowmapping.implementation.serializer.EidToLocatorRecordSerializer.java

public void serialize(ByteBuffer replyBuffer, EidToLocatorRecord record) {
    replyBuffer.putInt(NumberUtil.asInt(record.getRecordTtl()));
    if (record.getLocatorRecord() != null) {
        replyBuffer.put((byte) record.getLocatorRecord().size());
    } else {//from   ww w  .  java 2 s  . c  o m
        replyBuffer.put((byte) 0);
    }
    replyBuffer.put((byte) NumberUtil.asShort(record.getMaskLength()));
    Action act = Action.NoAction;
    if (record.getAction() != null) {
        act = record.getAction();
    }
    replyBuffer.put((byte) ((act.getIntValue() << 5) | //
            ByteUtil.boolToBit(BooleanUtils.isTrue(record.isAuthoritative()), Flags.AUTHORITATIVE)));
    replyBuffer.position(replyBuffer.position() + Length.RESERVED);
    replyBuffer.putShort(NumberUtil.asShort(record.getMapVersion()));
    if (record.getLispAddressContainer() != null && record.getLispAddressContainer().getAddress() != null) {
        LispAddressSerializer.getInstance().serialize(replyBuffer,
                LispAFIConvertor.toAFI(record.getLispAddressContainer()));
    }

    if (record.getLocatorRecord() != null) {
        for (LocatorRecord locatorRecord : record.getLocatorRecord()) {
            LocatorRecordSerializer.getInstance().serialize(replyBuffer, locatorRecord);
        }
    }
}