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:net.filterlogic.util.imaging.ToTIFF.java

private static String bigEndian2LittleEndian(String fileName) throws FileNotFoundException, IOException {

    //import java.nio.ByteBuffer;
    //import java.nio.ByteOrder;
    //import java.nio.channels.FileChannel;
    //import java.io.FileOutputStream;

    byte[] imgData = loadFileToByteArray(fileName);
    String newFileName = fileName + ".be2le.tif";

    ByteBuffer buffer = ByteBuffer.allocate(imgData.length);
    buffer.order(ByteOrder.LITTLE_ENDIAN);
    buffer.put(imgData);//from   w w  w . ja va  2  s .c  om
    FileChannel out = new FileOutputStream(newFileName).getChannel();
    out.write(buffer);
    out.close();

    return newFileName;
}

From source file:org.nuras.mcpha.Client.java

/**
 * Get histogram data/*  w  w w .j  a  v a 2 s. co  m*/
 * 
 * @param chan
 * @return 
 * @throws java.io.IOException 
 */
synchronized public static IntBuffer mcphaGetHistogramData(long chan) throws IOException {
    sendCommand(MCPHA_COMMAND_READ_HISTOGRAM_DATA, chan, 0);

    DataInputStream in = new DataInputStream(deviceSocket.getInputStream());

    ByteBuffer data = ByteBuffer.allocate(65536);
    data.order(ByteOrder.nativeOrder());
    in.readFully(data.array());

    return data.asIntBuffer();
}

From source file:org.nuras.mcpha.Client.java

/**
 * Get oscilloscope data which are 16-bit signed integer values.
 * The channels are interleaved sample-by-sample (ch1, ch2, ch1, ch2, etc).
 * //from w w  w  . jav  a2s .  c  o  m
 * @return a ShortBuffer of channel data values.
 * @throws java.io.IOException 
 */
synchronized public static ShortBuffer mcphaGetOsilloscopeData() throws IOException {
    sendCommand(MCPHA_COMMAND_READ_OSCILLOSCOPE_DATA, 0L, 0L);

    DataInputStream in = new DataInputStream(deviceSocket.getInputStream());

    ByteBuffer data = ByteBuffer.allocate(65536);
    data.order(ByteOrder.nativeOrder());
    in.readFully(data.array());

    return data.asShortBuffer();
}

From source file:com.kactech.otj.Utils.java

public static ByteBuffer seal(String msg, String nymID, PublicKey nymKey, SecretKeySpec aesSecret,
        IvParameterSpec vector) throws InvalidKeyException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    ByteBuffer buff = ByteBuffer.allocate(msg.length() + 500);//donno?
    buff.order(ByteOrder.BIG_ENDIAN);
    buff.putShort((short) 1);//asymmetric
    buff.putInt(1);//array size
    buff.putInt(nymID.length() + 1);// w  w w  .ja  va2  s  . co  m
    buff.put(bytes(nymID + '\0', US_ASCII));

    // create encoded key and message
    Cipher cipher;
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.ENCRYPT_MODE, aesSecret, vector);
    byte[] encrypted = cipher.doFinal(bytes(msg + '\0', UTF8));
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.WRAP_MODE, nymKey);
    byte[] encKeyBytes = cipher.wrap(aesSecret);

    buff.putInt(encKeyBytes.length);
    buff.put(encKeyBytes);
    buff.putInt(vector.getIV().length);
    buff.put(vector.getIV());
    buff.put(encrypted);
    buff.flip();

    return buff;
}

From source file:com.kactech.otj.Utils.java

public static String open(byte[] encryptedEnvelope, PrivateKey privateKey)
        throws InvalidKeyException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        IllegalBlockSizeException, BadPaddingException {
    String str;/*  ww w  .  j av a  2 s.c  o m*/
    byte[] by;
    ByteBuffer buff = ByteBuffer.wrap(encryptedEnvelope);
    buff.order(ByteOrder.BIG_ENDIAN);
    int envType = buff.getShort();// expected 1(asymmetric)
    if (envType != 1)
        throw new UnsupportedOperationException("unexpected envelope type " + envType);
    int arraySize = buff.getInt();// can result in negative integer but not expecting it here
    if (arraySize != 1)//TODO
        throw new UnsupportedOperationException("current code doesn't support multi-nym response");
    byte[] encKeyBytes = null;
    byte[] vectorBytes = null;
    for (int i = 0; i < arraySize; i++) {
        int nymIDLen = buff.getInt();
        by = new byte[nymIDLen];
        buff.get(by);
        String nymID;
        try {
            nymID = new String(by, 0, by.length - 1, Utils.US_ASCII);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        } // take nymID W/O trailing \0
          //TODO nymID matching!
        int keyLength = buff.getInt();
        encKeyBytes = new byte[keyLength];
        buff.get(encKeyBytes);
        int vectorLength = buff.getInt();
        vectorBytes = new byte[vectorLength];
        buff.get(vectorBytes);

    }
    byte[] encryptedMsg = new byte[buff.remaining()];
    buff.get(encryptedMsg);

    Cipher cipher;
    try {
        cipher = Cipher.getInstance(WRAP_ALGO);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.UNWRAP_MODE, privateKey);
    SecretKeySpec aesKey = (SecretKeySpec) cipher.unwrap(encKeyBytes, "AES", Cipher.SECRET_KEY);
    try {
        cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    cipher.init(Cipher.DECRYPT_MODE, aesKey, new IvParameterSpec(vectorBytes));
    by = cipher.doFinal(encryptedMsg);
    try {
        str = new String(by, 0, by.length - 1, Utils.UTF8);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    } // w/o trailing \0
    return str;
}

From source file:edu.mbl.jif.imaging.mmtiff.MultipageTiffReader.java

public static boolean isMMMultipageTiff(String directory) throws IOException {
    File dir = new File(directory);
    File[] children = dir.listFiles();
    File testFile = null;//from   ww  w . j  a v a 2  s. c o m
    for (File child : children) {
        if (child.isDirectory()) {
            File[] grandchildren = child.listFiles();
            for (File grandchild : grandchildren) {
                if (grandchild.getName().endsWith(".tif")) {
                    testFile = grandchild;
                    break;
                }
            }
        } else if (child.getName().endsWith(".tif") || child.getName().endsWith(".TIF")) {
            testFile = child;
            break;
        }
    }
    if (testFile == null) {
        throw new IOException("Unexpected file structure: is this an MM dataset?");
    }
    RandomAccessFile ra;
    try {
        ra = new RandomAccessFile(testFile, "r");
    } catch (FileNotFoundException ex) {
        ReportingUtils.logError(ex);
        return false;
    }
    FileChannel channel = ra.getChannel();
    ByteBuffer tiffHeader = ByteBuffer.allocate(36);
    ByteOrder bo;
    channel.read(tiffHeader, 0);
    char zeroOne = tiffHeader.getChar(0);
    if (zeroOne == 0x4949) {
        bo = ByteOrder.LITTLE_ENDIAN;
    } else if (zeroOne == 0x4d4d) {
        bo = ByteOrder.BIG_ENDIAN;
    } else {
        throw new IOException("Error reading Tiff header");
    }
    tiffHeader.order(bo);
    int summaryMDHeader = tiffHeader.getInt(32);
    channel.close();
    ra.close();
    if (summaryMDHeader == MultipageTiffWriter.SUMMARY_MD_HEADER) {
        return true;
    }
    return false;
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

public static GTSDecoder fromBlock(byte[] block, byte[] key) throws IOException {

    if (block.length < 6) {
        throw new IOException("Invalid block.");
    }//  ww w  .  j av a2 s  .co m

    ByteBuffer buffer = ByteBuffer.wrap(block);

    //
    // Extract size
    //

    buffer.order(ByteOrder.BIG_ENDIAN);
    int size = buffer.getInt();

    // Check size

    if (block.length != size) {
        throw new IOException("Invalid block size, expected " + size + ", block is " + block.length);
    }

    // Extract compression

    byte comp = buffer.get();

    boolean compress = false;

    if (0 == comp) {
        compress = false;
    } else if (1 == comp) {
        compress = true;
    } else {
        throw new IOException("Invalid compression flag");
    }

    // Extract base timestamp

    long base = Varint.decodeSignedLong(buffer);

    InputStream in;

    ByteArrayInputStream bain = new ByteArrayInputStream(block, buffer.position(), buffer.remaining());

    if (compress) {
        in = new GZIPInputStream(bain);
    } else {
        in = bain;
    }

    byte[] buf = new byte[1024];

    ByteArrayOutputStream out = new ByteArrayOutputStream(buffer.remaining());

    while (true) {
        int len = in.read(buf);

        if (len <= 0) {
            break;
        }
        out.write(buf, 0, len);
    }

    GTSDecoder decoder = new GTSDecoder(base, key, ByteBuffer.wrap(out.toByteArray()));

    return decoder;
}

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

/**
 * Serializes an End-Of-Period Marker onto the ByteBuffer passed in.
 * @param serializationBuffer - The ByteBuffer to serialize the event in. The buffer must have enough space to accommodate
 *                              the event. (76 bytes)
 * @param eventInfo - The timestamp to use for the EOP marker
 * @return the number of bytes written//w ww  . j av a  2  s.  c  o m
 */
public static int serializeEndOfPeriodMarker(ByteBuffer serializationBuffer, DbusEventInfo eventInfo) {
    byte[] attributes = (serializationBuffer.order() == ByteOrder.BIG_ENDIAN) ? EmptyAttributesBigEndian
            : EmptyAttributesLittleEndian;
    return serializeFullEvent(DbusEventInternalWritable.EOPMarkerKey.getLongKey(), serializationBuffer,
            eventInfo, attributes);
}

From source file:org.dragonet.entity.metadata.type.ByteArrayMeta.java

@Override
public byte[] encode() {
    ByteBuffer buff = ByteBuffer.allocate(2 + this.data.length);
    buff.order(ByteOrder.LITTLE_ENDIAN);
    buff.putShort((short) (this.data.length & 0xFFFF));
    buff.put(this.data);
    return buff.array();
}

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

/**
 * Exposing this method only until we fix DDSDBUS-2282 is fixed.
 * DO NOT USE THIS METHOD EVEN IN TESTS.
 */// www .ja v a  2  s . c  o  m
protected static int serializeFullEventWithEmptyAttributes(long key, ByteBuffer buf, DbusEventInfo eventInfo) {
    return serializeFullEvent(key, buf, eventInfo,
            (buf.order() == ByteOrder.BIG_ENDIAN) ? EmptyAttributesBigEndian : EmptyAttributesLittleEndian);
}