Example usage for java.nio ByteBuffer array

List of usage examples for java.nio ByteBuffer array

Introduction

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

Prototype

public final byte[] array() 

Source Link

Document

Returns the byte array which this buffer is based on, if there is one.

Usage

From source file:com.glaf.core.util.ByteBufferUtils.java

/**
 * Transfer bytes from one ByteBuffer to another. This function acts as
 * System.arrayCopy() but for ByteBuffers.
 * /*from w w  w.  ja v  a2  s. c  o m*/
 * @param src
 *            the source ByteBuffer
 * @param srcPos
 *            starting position in the source ByteBuffer
 * @param dst
 *            the destination ByteBuffer
 * @param dstPos
 *            starting position in the destination ByteBuffer
 * @param length
 *            the number of bytes to copy
 */
public static void arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) {
    if (src.hasArray() && dst.hasArray()) {
        System.arraycopy(src.array(), src.arrayOffset() + srcPos, dst.array(), dst.arrayOffset() + dstPos,
                length);
    } else {
        if (src.limit() - srcPos < length || dst.limit() - dstPos < length)
            throw new IndexOutOfBoundsException();

        for (int i = 0; i < length; i++)

            dst.put(dstPos++, src.get(srcPos++));
    }
}

From source file:net.beaconcontroller.tutorial.LearningSwitchTutorial.java

/**
 * TODO: Learn the source MAC:port pair for each arriving packet. Next send
 * the packet out the port previously learned for the destination MAC, if it
 * exists. Otherwise flood the packet similarly to forwardAsHub.
 * // w  ww .j  a  va 2 s. co  m
 * @param sw
 *            the OpenFlow switch object
 * @param pi
 *            the OpenFlow Packet In object
 * @throws IOException
 */
/*
 * public void forwardAsLearningSwitch(IOFSwitch sw, OFPacketIn pi) throws
 * IOException { Map<Long,Short> macTable = macTables.get(sw);
 * 
 * /** START HERE: You'll find descriptions of what needs to be done below
 * here, and starter pseudo code. Your job is to uncomment and replace the
 * pseudo code with actual Java code.
 * 
 * First build the OFMatch object that will be used to match packets from
 * this new flow. See the OFMatch and OFPacketIn class Javadocs, which if
 * you are using the tutorial archive, are in the apidocs folder where you
 * extracted it.
 * 
 * OFMatch match = new OFMatch(); match.loadFromPacket(pi.getPacketData(),
 * pi.getInPort()); byte[] dlDst = match.getDataLayerDestination(); Long
 * dlDstId = Ethernet.toLong(dlDst); byte[] dlSrc =
 * match.getDataLayerSource(); Long dlSrcId = Ethernet.toLong(dlSrc); int
 * bufferId = pi.getBufferId();
 * 
 * /** Learn that the host with the source MAC address in this packet is
 * reachable at the port this packet arrived on. Put this source MAC:port
 * pair into the macTable object for future lookups. HINT: you can use
 * Ethernet.toLong to convert from byte[] to Long, which is the key for the
 * macTable Map object.
 * 
 * macTable.put(dlSrcId,pi.getInPort());
 * log.info("Learned MAC address {} is at port {}", dlSrcId,
 * pi.getInPort());
 * 
 * /** Retrieve the port this packet should be sent out by getting the port
 * associated with the destination MAC address in this packet from the
 * macTable object.
 * 
 * Short outPort = null; if (macTable.containsKey(dlDstId)) outPort =
 * macTable.get(dlDstId);
 * 
 * if(outPort!=null){
 * 
 * }else {
 * 
 * }
 * 
 * /** If the outPort is known for the MAC address (the return value from
 * macTable is not null), then Phase 1: Create and send an OFPacketOut,
 * sending it to the outPort learned previously. After this is tested and
 * works move to phase 2.
 * 
 * Phase 2: Instead of an OFPacketOut, create and send an OFFlowMod using
 * the match created earlier from the packet, and send matched packets to
 * the outPort. For extra credit, after sending the OFFlowMod, send an
 * OFPacketOut, but only if the switch did not buffer the packet
 * (pi.getBufferId() == OFPacketOut.BUFFER_ID_NONE), and be sure to set the
 * OFPacketOut's data with the data in pi.
 * 
 * Else if the outPort is not known (return value from macTable is null),
 * then use the forwardAsHub method to send an OFPacketOut that floods out
 * all ports except the port the packet came in.
 * 
 * 
 * // if (outPort != null) { // Phase 1: // OFPacketOut po = ... // ... fill
 * in po, unicast to outPort // ... send po to the switch // // Phase 2: //
 * Comment out the code from phase 1 // OFFlowMod fm = ... // ... fill in fm
 * // ... send fm to the switch // Extra credit: // if (...) { //
 * OFPacketOut po = ... // ... fill in po, unicast to outPort // ... set
 * po's data from pi's data // ... send po to the switch // } //} else { //
 * forwardAsHub(sw, pi); //} }
 */

public static void forwardAsLearningSwitch(IOFSwitch sw, OFPacketIn pi) throws IOException {
    Map<Long, Short> macTable = macTables.get(sw);

    // Build the Match
    OFMatch match = OFMatch.load(pi.getPacketData(), pi.getInPort());

    // Learn the port to reach the packet's source MAC
    macTable.put(Ethernet.toLong(match.getDataLayerSource()), pi.getInPort());

    // Retrieve the port previously learned for the packet's dest MAC
    Short outPort = macTable.get(Ethernet.toLong(match.getDataLayerDestination()));
    byte[] dlDst = match.getDataLayerDestination();
    Long dlDstId = Ethernet.toLong(dlDst);
    byte[] dlSrc = match.getDataLayerSource();
    Long dlSrcId = Ethernet.toLong(dlSrc);
    int bufferId = pi.getBufferId();

    //  JSONObject doc = new JSONObject();
    HashMap doc = new HashMap();
    doc.put(("OF_PACKETS_DEST"), dlDstId);
    doc.put(("OF_PACKETS_SRC"), dlSrcId);
    doc.put(("OF_PACKETS_SRCPORT"), match.getInputPort());
    if (outPort != null) {
        doc.put(("OF_PACKETS_DESTPORT"), outPort);
    } else {
        doc.put(("OF_PACKETS_DESTPORT"), "Flood");
    }

    String netSrc = Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkSource()).toByteArray())
            .toString();
    netSrc = netSrc.substring(1, netSrc.length());
    //doc.put(("OF_PACKETS_NETSRC"),Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkSource()).toByteArray()).toString());
    doc.put(("OF_PACKETS_NETSRC"), netSrc);
    String netDest = Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkDestination()).toByteArray())
            .toString();
    netDest = netDest.substring(1, netDest.length());

    doc.put(("OF_PACKETS_NETDEST"), Inet4Address
            .getByAddress(BigInteger.valueOf(match.getNetworkDestination()).toByteArray()).toString());

    doc.put(("OF_PACKETS_NETDEST"), netDest);
    doc.put(("OF_PACKETS_SWITCHID"), sw.getId());
    ByteBuffer datap = ByteBuffer.allocate(pi.getLength());
    pi.writeTo(datap);
    doc.put(("OF_PACKETS_OBJ"), datap.array());
    doc.put(("OF_PACKETS_PACKETTYPE"), pi.getType().toString());
    doc.put(("OF_PACKETS_TIMESTAMP"), System.currentTimeMillis());

    try {
        System.out.println("Src:" + dlSrcId + " Dst:" + dlDstId + "SWID:" + sw.getId());
    } catch (Exception exp) {
        System.out.println(exp.toString());
    }

    System.out.println("1" + match.getInputPort());
    System.out.println("2"
            + Inet4Address.getByAddress(BigInteger.valueOf(match.getNetworkSource()).toByteArray()).toString());
    System.out.println("3" + Inet4Address
            .getByAddress(BigInteger.valueOf(match.getNetworkDestination()).toByteArray()).toString());
    System.out.println(
            "4" + match.getNetworkTypeOfService() + " -- " + Ethernet.toLong(match.getDataLayerSource()));

    try {
        IPv4 ipd = new IPv4();
        ipd.deserialize(pi.getPacketData(), 0, pi.getPacketData().length);
        System.out.println("IP::" + ipd.getIdentification());
        doc.put(("OF_PACKETS_IDEN"), (Short) ipd.getIdentification());
    } catch (Exception e) {
        //e.printStackTrace();
    }

    System.out.println("5 " + pi.getPacketData());

    //SDNDe sdnde = new SDNDe(db);

    if (Settings.isSet() && Settings.BREAKPOINT.equals(Settings.getFnName())
            && String.valueOf(sw.getId()).equals(Settings.getSid())
            && doc.get("OF_PACKETS_NETSRC").equals(Settings.getSrc())
            && doc.get("OF_PACKETS_NETDEST").equals(Settings.getDest())) {
        Settings.bkQ.add(new AbstractMap.SimpleEntry(sw, new AbstractMap.SimpleEntry(pi, doc)));
        System.out.println("In BreakPoint:" + Settings.bkQ.size());
        for (Entry e : Settings.bkQ)
            System.out.println("Entry:" + e.getKey() + "=" + e.getValue());
        SocketServer.sendAsyncPacket(Settings.BREAKPOINT, null);
        return;

    } else if (Settings.isSet() && Settings.MONITOR.equals(Settings.getFnName())
            && String.valueOf(sw.getId()).equals(Settings.getSid())
            && doc.get("OF_PACKETS_NETSRC").equals(Settings.getSrc())
            && doc.get("OF_PACKETS_NETDEST").equals(Settings.getDest())) {
        //Settings.bkQ.add(new AbstractMap.SimpleEntry(sw,new AbstractMap.SimpleEntry(pi, doc)));
        //Settings.bkQ.put((Long)sw.getId(), new AbstractMap.SimpleEntry(sw,pi));
        //System.out.println("In Monitor:"+Settings.bkQ.size());
        //for(Entry e:Settings.bkQ)
        //System.out.println("Entry:"+e.getKey()+"="+e.getValue());
        SocketServer.sendAsyncPacket(Settings.MONITOR, doc);
        //return;
    } else if (Settings.isSet() && Settings.STEP.equals(Settings.getFnName())
            && doc.get("OF_PACKETS_NETSRC").equals(Settings.getSrc())
            && doc.get("OF_PACKETS_NETDEST").equals(Settings.getDest())) {
        /*synchronized (Settings.bkQ) {
           Settings.bkQ.add(new AbstractMap.SimpleEntry(sw,new AbstractMap.SimpleEntry(pi, doc)));
            System.out.println("In Step:"+Settings.bkQ.size());
            for(Entry e:Settings.bkQ)
          System.out.println("Entry:"+e.getKey()+"="+e.getValue());
        }*/

        SocketServer.sendAsyncPacket(Settings.STEP, null);
        if (!Settings.getSid().equals(String.valueOf(sw.getId()))) {
            Settings.setFnName(Settings.BREAKPOINT);
            Settings.setSid(String.valueOf(sw.getId()));
            Settings.bkQ.add(new AbstractMap.SimpleEntry(sw, new AbstractMap.SimpleEntry(pi, doc)));
            return;
        }

    }
    db.createPacketInDB(doc);

    if (outPort != null) {
        // Destination port known, push down a flow
        OFFlowMod fm = new OFFlowMod();
        fm.setBufferId(pi.getBufferId());
        // Use the Flow ADD command
        fm.setCommand(OFFlowMod.OFPFC_ADD);
        // Time out the flow after 5 seconds if inactivity
        fm.setIdleTimeout((short) 5);
        // Match the packet using the match created above
        fm.setMatch(match);
        // Send matching packets to outPort
        OFAction action = new OFActionOutput(outPort);
        fm.setActions(Collections.singletonList((OFAction) action));
        // Send this OFFlowMod to the switch
        sw.getOutputStream().write(fm);

        if (pi.getBufferId() == OFPacketOut.BUFFER_ID_NONE) {
            /**
             * EXTRA CREDIT: This is a corner case, the packet was not
             * buffered at the switch so it must be sent as an OFPacketOut
             * after sending the OFFlowMod
             */
            OFPacketOut po = new OFPacketOut();
            action = new OFActionOutput(outPort);
            po.setActions(Collections.singletonList(action));
            po.setBufferId(OFPacketOut.BUFFER_ID_NONE);
            po.setInPort(pi.getInPort());
            po.setPacketData(pi.getPacketData());
            sw.getOutputStream().write(po);
        }
    } else {
        // Destination port unknown, flood packet to all ports
        forwardAsHub(sw, pi);
    }
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

public static String string(ByteBuffer bytes) {
    if (bytes == null) {
        return null;
    }//  ww  w.j ava2  s .c  o m
    return string(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.remaining(), UTF8_ENCODING);
}

From source file:com.github.nlloyd.hornofmongo.util.BSONizer.java

@SuppressWarnings("deprecation")
public static Object convertBSONtoJS(MongoScope mongoScope, Object bsonObject) {
    Object jsObject = null;/*ww  w .ja  v a2  s  .co m*/
    if (bsonObject instanceof List<?>) {
        List<?> bsonList = (List<?>) bsonObject;
        Scriptable jsArray = (Scriptable) MongoRuntime.call(new NewInstanceAction(mongoScope, bsonList.size()));

        int index = 0;
        for (Object bsonEntry : bsonList) {
            ScriptableObject.putProperty(jsArray, index, convertBSONtoJS(mongoScope, bsonEntry));
            index++;
        }

        jsObject = jsArray;
    } else if (bsonObject instanceof BSONObject) {
        Scriptable jsObj = (Scriptable) MongoRuntime.call(new NewInstanceAction(mongoScope));
        BSONObject bsonObj = (BSONObject) bsonObject;

        for (String key : bsonObj.keySet()) {
            Object value = convertBSONtoJS(mongoScope, bsonObj.get(key));
            MongoRuntime.call(new JSPopulatePropertyAction(jsObj, key, value));
        }
        jsObject = jsObj;
    } else if (bsonObject instanceof Symbol) {
        jsObject = ((Symbol) bsonObject).getSymbol();
    } else if (bsonObject instanceof Date) {
        jsObject = MongoRuntime.call(
                new NewInstanceAction(mongoScope, "Date", new Object[] { ((Date) bsonObject).getTime() }));
    } else if (bsonObject instanceof Pattern) {
        Pattern regex = (Pattern) bsonObject;
        String source = regex.pattern();
        String options = Bytes.regexFlags(regex.flags());
        jsObject = MongoRuntime
                .call(new NewInstanceAction(mongoScope, "RegExp", new Object[] { source, options }));
    } else if (bsonObject instanceof org.bson.types.ObjectId) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "ObjectId"));
        ((ObjectId) jsObject).setRealObjectId((org.bson.types.ObjectId) bsonObject);
    } else if (bsonObject instanceof org.bson.types.MinKey) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "MinKey"));
    } else if (bsonObject instanceof org.bson.types.MaxKey) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "MaxKey"));
    } else if (bsonObject instanceof com.mongodb.DBRef) {
        com.mongodb.DBRef dbRef = (com.mongodb.DBRef) bsonObject;
        Object id = convertBSONtoJS(mongoScope, dbRef.getId());
        jsObject = MongoRuntime.call(
                new NewInstanceAction(mongoScope, "DBRef", new Object[] { dbRef.getCollectionName(), id }));
    } else if (bsonObject instanceof BSONTimestamp) {
        BSONTimestamp bsonTstamp = (BSONTimestamp) bsonObject;
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "Timestamp",
                new Object[] { bsonTstamp.getTime(), bsonTstamp.getInc() }));
    } else if (bsonObject instanceof Long) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "NumberLong"));
        ((NumberLong) jsObject).setRealLong((Long) bsonObject);
    } else if (bsonObject instanceof Integer) {
        jsObject = Double.valueOf((Integer) bsonObject);
    } else if (bsonObject instanceof Code) {
        jsObject = ((Code) bsonObject).getCode();
    } else if (bsonObject instanceof byte[]) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData"));
        ((BinData) jsObject).setValues(0, (byte[]) bsonObject);
    } else if (bsonObject instanceof Binary) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData"));
        ((BinData) jsObject).setValues(((Binary) bsonObject).getType(), ((Binary) bsonObject).getData());
    } else if (bsonObject instanceof UUID) {
        jsObject = MongoRuntime.call(new NewInstanceAction(mongoScope, "BinData"));
        UUID uuid = (UUID) bsonObject;
        ByteBuffer dataBuffer = ByteBuffer.allocate(16);
        // mongodb wire protocol is little endian
        dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
        dataBuffer.putLong(uuid.getMostSignificantBits());
        dataBuffer.putLong(uuid.getLeastSignificantBits());
        ((BinData) jsObject).setValues(BSON.B_UUID, dataBuffer.array());
    } else {
        jsObject = bsonObject;
    }

    return jsObject;
}

From source file:com.sitewhere.hbase.device.HBaseDeviceEvent.java

/**
 * Creates a base 64 encoded String for unique event key.
 * /*from w w  w. j a v  a 2  s  . co m*/
 * @param rowkey
 * @param qualifier
 * @return
 */
public static String getEncodedEventId(byte[] rowkey, byte[] qualifier) {
    ByteBuffer buffer = ByteBuffer.allocate(rowkey.length + qualifier.length);
    buffer.put(rowkey);
    buffer.put(qualifier);
    return DatatypeConverter.printBase64Binary(buffer.array());
}

From source file:com.easemob.dataexport.utils.ConversionUtils.java

/**
 * @param val/*from  ww  w  . j av  a 2 s .  co m*/
 * @return
 */
public static byte[] bytes(Long val) {
    ByteBuffer buf = ByteBuffer.allocate(8);
    buf.order(ByteOrder.BIG_ENDIAN);
    buf.putLong(val);
    return buf.array();
}

From source file:com.glaf.core.util.ByteBufferUtils.java

/**
 * You should almost never use this. Instead, use the write* methods to
 * avoid copies.//  w w w .ja  v a  2 s. c  o m
 */
public static byte[] getArray(ByteBuffer buffer) {
    int length = buffer.remaining();

    if (buffer.hasArray()) {
        int boff = buffer.arrayOffset() + buffer.position();
        if (boff == 0 && length == buffer.array().length)
            return buffer.array();
        else
            return Arrays.copyOfRange(buffer.array(), boff, boff + length);
    }
    // else, DirectByteBuffer.get() is the fastest route
    byte[] bytes = new byte[length];
    buffer.duplicate().get(bytes);

    return bytes;
}

From source file:com.blm.orc.ReaderImpl.java

private static FileMetaInfo extractMetaInfoFromFooter(FileSystem fs, Path path, long maxFileLength)
        throws IOException {
    FSDataInputStream file = fs.open(path);

    // figure out the size of the file using the option or filesystem
    long size;//from ww  w.ja  v  a2 s .c  o  m
    if (maxFileLength == Long.MAX_VALUE) {
        size = fs.getFileStatus(path).getLen();
    } else {
        size = maxFileLength;
    }

    //read last bytes into buffer to get PostScript
    int readSize = (int) Math.min(size, DIRECTORY_SIZE_GUESS);
    file.seek(size - readSize);
    ByteBuffer buffer = ByteBuffer.allocate(readSize);
    file.readFully(buffer.array(), buffer.arrayOffset() + buffer.position(), buffer.remaining());

    //read the PostScript
    //get length of PostScript
    int psLen = buffer.get(readSize - 1) & 0xff;
    ensureOrcFooter(file, path, psLen, buffer);
    int psOffset = readSize - 1 - psLen;
    CodedInputStream in = CodedInputStream.newInstance(buffer.array(), buffer.arrayOffset() + psOffset, psLen);
    OrcProto.PostScript ps = OrcProto.PostScript.parseFrom(in);

    checkOrcVersion(LOG, path, ps.getVersionList());

    int footerSize = (int) ps.getFooterLength();
    int metadataSize = (int) ps.getMetadataLength();
    OrcFile.WriterVersion writerVersion;
    if (ps.hasWriterVersion()) {
        writerVersion = getWriterVersion(ps.getWriterVersion());
    } else {
        writerVersion = OrcFile.WriterVersion.ORIGINAL;
    }

    //check compression codec
    switch (ps.getCompression()) {
    case NONE:
        break;
    case ZLIB:
        break;
    case SNAPPY:
        break;
    case LZO:
        break;
    default:
        throw new IllegalArgumentException("Unknown compression");
    }

    //check if extra bytes need to be read
    int extra = Math.max(0, psLen + 1 + footerSize + metadataSize - readSize);
    if (extra > 0) {
        //more bytes need to be read, seek back to the right place and read extra bytes
        file.seek(size - readSize - extra);
        ByteBuffer extraBuf = ByteBuffer.allocate(extra + readSize);
        file.readFully(extraBuf.array(), extraBuf.arrayOffset() + extraBuf.position(), extra);
        extraBuf.position(extra);
        //append with already read bytes
        extraBuf.put(buffer);
        buffer = extraBuf;
        buffer.position(0);
        buffer.limit(footerSize + metadataSize);
    } else {
        //footer is already in the bytes in buffer, just adjust position, length
        buffer.position(psOffset - footerSize - metadataSize);
        buffer.limit(psOffset);
    }

    // remember position for later
    buffer.mark();

    file.close();

    return new FileMetaInfo(ps.getCompression().toString(), (int) ps.getCompressionBlockSize(),
            (int) ps.getMetadataLength(), buffer, ps.getVersionList(), writerVersion);
}

From source file:com.healthmarketscience.jackcess.impl.OleUtil.java

private static String readStr(ByteBuffer bb, int off, int len, Charset charset) {
    String str = new String(bb.array(), off, len, charset);
    bb.position(off + len);/*  w w  w  . j  a  va  2s .c  o m*/
    if (str.charAt(str.length() - 1) == '\0') {
        str = str.substring(0, str.length() - 1);
    }
    return str;
}

From source file:com.sitewhere.hbase.device.HBaseDeviceEvent.java

/**
 * Get column qualifier for storing the event.
 * //from   www  .  j a va2  s .  co m
 * @param type
 * @param time
 * @return
 */
public static byte[] getQualifier(DeviceAssignmentRecordType eventType, long time) {
    time = time / 1000;
    long offset = time % BUCKET_INTERVAL;
    byte[] offsetBytes = Bytes.toBytes(offset);
    ByteBuffer buffer = ByteBuffer.allocate(4);
    buffer.put((byte) ~offsetBytes[5]);
    buffer.put((byte) ~offsetBytes[6]);
    buffer.put((byte) ~offsetBytes[7]);
    buffer.put(eventType.getType());
    return buffer.array();
}