Example usage for java.nio ByteBuffer order

List of usage examples for java.nio ByteBuffer order

Introduction

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

Prototype

Endianness order

To view the source code for java.nio ByteBuffer order.

Click Source Link

Document

The byte order of this buffer, default is BIG_ENDIAN .

Usage

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

private static int serializeLongKeyEvent(long key, ByteBuffer serializationBuffer, DbusEventInfo eventInfo) {
    byte[] attributes = null;

    // Event without explicit opcode specified should always be considered UPSERT or existing code will break
    if (eventInfo.getOpCode() == DbusOpcode.DELETE) {
        if (serializationBuffer.order() == ByteOrder.BIG_ENDIAN)
            attributes = DeleteLongKeyAttributesBigEndian.clone();
        else//from  w ww .j a  v  a2 s.c om
            attributes = DeleteLongKeyAttributesLittleEndian.clone();
    } else {
        if (serializationBuffer.order() == ByteOrder.BIG_ENDIAN)
            attributes = UpsertLongKeyAttributesBigEndian.clone();
        else
            attributes = UpsertLongKeyAttributesLittleEndian.clone();
    }

    if (eventInfo.isEnableTracing()) {
        setTraceFlag(attributes, serializationBuffer.order());
    }
    if (eventInfo.isReplicated())
        setExtReplicationFlag(attributes, serializationBuffer.order());

    return serializeFullEvent(key, serializationBuffer, eventInfo, attributes);
}

From source file:io.fabric8.maven.docker.access.log.LogRequestor.java

private boolean readStreamFrame(InputStream is) throws IOException, LogCallback.DoneException {
    // Read the header, which is composed of eight bytes. The first byte is an integer
    // indicating the stream type (0 = stdin, 1 = stdout, 2 = stderr), the next three are thrown
    // out, and the final four are the size of the remaining stream as an integer.
    ByteBuffer headerBuffer = ByteBuffer.allocate(8);
    headerBuffer.order(ByteOrder.BIG_ENDIAN);
    try {//from   w ww . j a v a 2s. co m
        this.readFully(is, headerBuffer.array());
    } catch (NoBytesReadException e) {
        // Not bytes read for stream. Return false to stop consuming stream.
        return false;
    } catch (EOFException e) {
        throw new IOException("Failed to read log header. Could not read all 8 bytes. " + e.getMessage(), e);
    }

    // Grab the stream type (stdout, stderr, stdin) from first byte and throw away other 3 bytes.
    int type = headerBuffer.get();

    // Skip three bytes, then read size from remaining four bytes.
    int size = headerBuffer.getInt(4);

    // Ignore empty messages and keep reading.
    if (size <= 0) {
        return true;
    }

    // Read the actual message
    ByteBuffer payload = ByteBuffer.allocate(size);
    try {
        ByteStreams.readFully(is, payload.array());
    } catch (EOFException e) {
        throw new IOException("Failed to read log message. Could not read all " + size + " bytes. "
                + e.getMessage() + " [ Header: " + Hex.encodeHexString(headerBuffer.array()) + "]", e);
    }

    String message = Charsets.UTF_8.newDecoder().decode(payload).toString();
    callLogCallback(type, message);
    return true;
}

From source file:uk.ac.cam.cl.dtg.picky.parser.pcap2.PcapParser.java

private byte[] toPCAPFormat(Packet packet) {
    ByteArrayBuffer buffer = new ByteArrayBuffer(50);

    ByteBuffer b = ByteBuffer.allocate(16);
    b.order(ByteOrder.LITTLE_ENDIAN);

    // guint32 ts_sec; /* timestamp seconds */
    putUnsignedInt(b, pcap.getTimestamp().getTime() / 1000);

    // guint32 ts_usec; /* timestamp microseconds */
    putUnsignedInt(b, (pcap.getTimestamp().getTime() - pcap.getTimestamp().getTime() / 1000 * 1000));

    // guint32 incl_len; /* number of octets of packet saved in file */
    putUnsignedInt(b, packet.getRawData().length);

    // guint32 orig_len; /* actual length of packet */
    putUnsignedInt(b, packet.length());//w  w  w. ja  va  2s  . c om
    // FIXME: putUnsignedInt(b, packet.getOriginalLength());

    buffer.append(b.array(), 0, 16);
    buffer.append(packet.getRawData(), 0, packet.getRawData().length);

    return buffer.toByteArray();
}

From source file:org.jmangos.sniffer.network.model.impl.WOWNetworkChannel.java

@Override
synchronized public void onResiveServerData(final long frameNumber, final byte[] buffer) {
    final ByteBuffer bytebuf = ByteBuffer.wrap(buffer);
    bytebuf.order(ByteOrder.LITTLE_ENDIAN);
    long opcode = 0;
    long size = 0;
    byte[] data = null;
    if (getChannelState().contains(State.AUTHED)) {
        final long header = bytebuf.getInt() & 0xFFFFFFFF;
        size = header >> 13;// w  w w  .  ja va  2  s  .c o  m
        opcode = header & 0x1FFF;
        data = new byte[(int) size];
        bytebuf.get(data);
    } else {
        size = bytebuf.getShort();
        opcode = bytebuf.getInt();
        bytebuf.mark();
        data = new byte[(int) size - 4];
        bytebuf.get(data);
        bytebuf.reset();
        // old 0xc0b
        if ((opcode == 0x221) & !getChannelState().contains(State.NOT_ACCEPT_SEED)) {
            this.log.debug("Get new Seed");
            final byte[] serverSeed = new byte[16];
            final byte[] clientSeed = new byte[16];
            for (int i = 0; i < 16; i++) {
                serverSeed[i] = bytebuf.get();
            }
            for (int i = 0; i < 16; i++) {
                clientSeed[i] = bytebuf.get();
            }
            bytebuf.get();
            this.csPacketBuffer.getCrypt().setEncryptionSeed(clientSeed);
            this.scPacketBuffer.getCrypt().setEncryptionSeed(serverSeed);
        }

    }
    this.log.debug(String.format("Frame: %d; Resive packet %s Opcode: 0x%x OpcodeSize: %d", frameNumber, "SMSG",
            opcode, size));
    for (final PacketLogHandler logger : this.packetLoggers) {
        logger.onDecodePacket(this, Direction.SERVER, (int) size, (int) opcode, data, (int) frameNumber);
    }
}

From source file:com.example.ex_templete.TouchRotateFragment.java

public Cube() {
    int one = 0x10000;
    int vertices[] = { -one, -one, -one, one, -one, -one, one, one, -one, -one, one, -one, -one, -one, one, one,
            -one, one, one, one, one, -one, one, one, };

    int colors[] = { 0, 0, 0, one, one, 0, 0, one, one, one, 0, one, 0, one, 0, one, 0, 0, one, one, one, 0,
            one, one, one, one, one, one, 0, one, one, one, };

    byte indices[] = { 0, 4, 5, 0, 5, 1, 1, 5, 6, 1, 6, 2, 2, 6, 7, 2, 7, 3, 3, 7, 4, 3, 4, 0, 4, 7, 6, 4, 6, 5,
            3, 0, 1, 3, 1, 2 };//from w  w  w.java  2s  . c o  m

    // Buffers to be passed to gl*Pointer() functions
    // must be direct, i.e., they must be placed on the
    // native heap where the garbage collector cannot
    // move them.
    //
    // Buffers with multi-byte datatypes (e.g., short, int, float)
    // must have their byte order set to native order

    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
    vbb.order(ByteOrder.nativeOrder());
    mVertexBuffer = vbb.asIntBuffer();
    mVertexBuffer.put(vertices);
    mVertexBuffer.position(0);

    ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
    cbb.order(ByteOrder.nativeOrder());
    mColorBuffer = cbb.asIntBuffer();
    mColorBuffer.put(colors);
    mColorBuffer.position(0);

    mIndexBuffer = ByteBuffer.allocateDirect(indices.length);
    mIndexBuffer.put(indices);
    mIndexBuffer.position(0);
}

From source file:Main.java

private static ByteBuffer convertImageData(BufferedImage bufferedImage) {
    ByteBuffer imageBuffer;
    WritableRaster raster;//w  w w. ja  va2  s . co  m
    BufferedImage texImage;

    // for a texture
    if (bufferedImage.getColorModel().hasAlpha()) {
        raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, bufferedImage.getWidth(),
                bufferedImage.getHeight(), 4, null);
        texImage = new BufferedImage(glAlphaColorModel, raster, false, new Hashtable<Object, Object>());
    } else {
        raster = Raster.createInterleavedRaster(DataBuffer.TYPE_BYTE, bufferedImage.getWidth(),
                bufferedImage.getHeight(), 3, null);
        texImage = new BufferedImage(glColorModel, raster, false, new Hashtable<Object, Object>());
    }

    // copy the source image into the produced image
    Graphics g = texImage.getGraphics();
    g.setColor(new Color(0f, 0f, 0f, 0f));
    g.fillRect(0, 0, bufferedImage.getWidth(), bufferedImage.getHeight());
    g.drawImage(bufferedImage, 0, 0, null);

    // build a byte buffer from the temporary image
    // that be used by OpenGL to produce a texture.
    byte[] data = ((DataBufferByte) bufferedImage.getRaster().getDataBuffer()).getData();

    imageBuffer = ByteBuffer.allocateDirect(data.length);
    imageBuffer.order(ByteOrder.nativeOrder());
    imageBuffer.put(data, 0, data.length);
    imageBuffer.flip();

    return imageBuffer;
}

From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java

private void patchGame() throws IOException {
    /*//from  w w  w  . j av  a  2 s. co  m
     * Custom patch format (config/game-patch.bin) is as follows:
     * 0x8 byte little endian: Address in game image to start patching
     * 0x8 byte little endian: Length of patch
     * If there are more patches, repeat after reading the length of patch
     * Note that all games will be patched the same way, so if a game is broken before patching, it will still be broken!
     */
    nextStep("Patching game.");
    File gamePatch = new File(mTempDir, "/config/game-patch.bin");
    if (!gamePatch.exists())
        return;
    Logger.info("Making a copy of game.");
    File tempGame = new File(mTempDir, "game.iso");
    FileUtils.copyFile(mInputFile, tempGame);
    RandomAccessFile game = new RandomAccessFile(tempGame, "rw");
    InputStream patch = new FileInputStream(gamePatch);
    while (true) {
        byte[] rawPatchAddr = new byte[8];
        byte[] rawPatchLen = new byte[8];
        if (patch.read(rawPatchAddr) + patch.read(rawPatchLen) < rawPatchAddr.length + rawPatchLen.length)
            break;
        ByteBuffer bb = ByteBuffer.wrap(rawPatchAddr);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        long patchAddr = bb.getLong();
        bb = ByteBuffer.wrap(rawPatchLen);
        bb.order(ByteOrder.LITTLE_ENDIAN);
        long patchLen = bb.getLong();

        game.seek(patchAddr);
        while (patchLen-- > 0) {
            game.write(patch.read());
        }
    }
    mInputFile = tempGame;
    game.close();
    patch.close();
    Logger.debug("Done patching game.");
}

From source file:io.gomint.server.network.packet.PacketLogin.java

@Override
public void deserialize(PacketBuffer buffer) {
    this.protocol = buffer.readInt();

    // Decompress inner data (i don't know why you compress inside of a Batched Packet but hey)
    byte[] compressed = new byte[buffer.readInt()];
    buffer.readBytes(compressed);/*from ww w  . j  a  v  a  2 s. co m*/

    Inflater inflater = new Inflater();
    inflater.setInput(compressed);

    ByteArrayOutputStream bout = new ByteArrayOutputStream();

    try {
        byte[] comBuffer = new byte[1024];
        while (!inflater.finished()) {
            int read = inflater.inflate(comBuffer);
            bout.write(comBuffer, 0, read);
        }
    } catch (DataFormatException e) {
        System.out.println("Failed to decompress batch packet" + e);
        return;
    }

    // More data please
    ByteBuffer byteBuffer = ByteBuffer.wrap(bout.toByteArray());
    byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
    byte[] stringBuffer = new byte[byteBuffer.getInt()];
    byteBuffer.get(stringBuffer);

    // Decode the json stuff
    try {
        JSONObject jsonObject = (JSONObject) new JSONParser().parse(new String(stringBuffer));
        JSONArray chainArray = (JSONArray) jsonObject.get("chain");
        if (chainArray != null) {
            this.validationKey = parseBae64JSON((String) chainArray.get(chainArray.size() - 1)); // First key in chain is last response in chain #brainfuck :D
            for (Object chainObj : chainArray) {
                decodeBase64JSON((String) chainObj);
            }
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }

    // Skin comes next
    this.skin = new byte[byteBuffer.getInt()];
    byteBuffer.get(this.skin);
}

From source file:au.org.ala.delta.translation.dist.DistItemsFileWriter.java

protected Pair<List<Integer>, List<Integer>> writeItems(int[] wordOffsets, int[] bitOffsets) {
    final int BYTES_IN_WORD = 4;
    List<Integer> itemRecords = new ArrayList<Integer>();
    List<Integer> nameLengths = new ArrayList<Integer>();
    int size = BinaryKeyFile.RECORD_LENGTH_BYTES;
    for (int offset : wordOffsets) {
        size = Math.max(size, offset);
    }//from ww  w. j  a va  2  s  . c  o  m
    Iterator<Item> items = _dataSet.unfilteredItems();
    while (items.hasNext()) {
        Item item = items.next();
        String description = _itemFormatter.formatItemDescription(item);
        nameLengths.add(description.length());
        byte[] bytes = new byte[(size + 1) * BYTES_IN_WORD];
        Arrays.fill(bytes, (byte) 0);

        ByteBuffer work = ByteBuffer.wrap(bytes);
        work.order(ByteOrder.LITTLE_ENDIAN);

        Iterator<IdentificationKeyCharacter> chars = _dataSet.unfilteredIdentificationKeyCharacterIterator();
        while (chars.hasNext()) {
            IdentificationKeyCharacter keyChar = chars.next();
            int charNum = keyChar.getCharacterNumber();
            if (!keyChar.getCharacterType().isText()) {
                int offset = wordOffsets[keyChar.getCharacterNumber() - 1] - 1;
                if (!(keyChar.getCharacterType() == CharacterType.UnorderedMultiState)) {
                    work.putFloat(offset * BYTES_IN_WORD, -9999.0f);
                }
                Attribute attribute = item.getAttribute(keyChar.getCharacter());
                if (attribute == null || attribute.isUnknown()) {
                    continue;
                }
                switch (keyChar.getCharacterType()) {
                case UnorderedMultiState:
                    encodeUnorderedMultistateAttribute(work, wordOffsets[charNum - 1] - 1,
                            bitOffsets[charNum - 1], keyChar, (MultiStateAttribute) attribute);

                    break;
                case OrderedMultiState:
                    encodeOrderedMultistateAttribute(work, wordOffsets[charNum - 1] - 1, keyChar,
                            (MultiStateAttribute) attribute);
                    break;
                case IntegerNumeric:
                case RealNumeric:
                    encodeNumericAttribute(work, wordOffsets[charNum - 1] - 1, keyChar,
                            (NumericAttribute) attribute);

                    break;
                }
            }

        }
        itemRecords.add(_itemsFile.writeItem(description, work));
    }
    return new Pair<List<Integer>, List<Integer>>(itemRecords, nameLengths);
}

From source file:org.jmangos.sniffer.network.model.impl.WOWNetworkChannel.java

@Override
public void onResiveClientData(final long frameNumber, final byte[] buffer) {
    final ByteBuffer bytebuf = ByteBuffer.wrap(buffer);
    long opcode = 0;
    long size = 0;
    byte[] data;// w  w  w.  j  a v  a2  s  .co m
    bytebuf.order(ByteOrder.LITTLE_ENDIAN);
    if (getChannelState().contains(State.AUTHED)) {
        final long header = bytebuf.getInt() & 0xFFFFFFFF;
        size = header >> 13;
        opcode = (header & 0x1FFF);
        data = new byte[(int) size];
        bytebuf.get(data);
    } else {
        size = bytebuf.getShort();
        opcode = bytebuf.getInt();
        data = new byte[(int) size - 4];
        bytebuf.get(data);
        // old (opcode == 0x1a72) | (opcode == 0x3f3)
        if ((opcode == 0x1aa1) | (opcode == 0x9f1)) {
            this.log.debug("Init cryptography system for channel {}", this.getChannelId());
            addChannelState(State.AUTHED);
            this.csPacketBuffer.getCrypt().init(this.woWKeyReader.getKey());
            this.scPacketBuffer.getCrypt().init(this.woWKeyReader.getKey());
        }
    }
    this.log.debug(String.format("Frame: %d; Resive packet %s Opcode: 0x%x\n", frameNumber, "CMSG", opcode));
    for (final PacketLogHandler logger : this.packetLoggers) {
        logger.onDecodePacket(this, Direction.CLIENT, (int) size, (int) opcode, data, (int) frameNumber);
    }
}