Example usage for java.nio ByteOrder LITTLE_ENDIAN

List of usage examples for java.nio ByteOrder LITTLE_ENDIAN

Introduction

In this page you can find the example usage for java.nio ByteOrder LITTLE_ENDIAN.

Prototype

ByteOrder LITTLE_ENDIAN

To view the source code for java.nio ByteOrder LITTLE_ENDIAN.

Click Source Link

Document

This constant represents little endian.

Usage

From source file:ru.jts_dev.authserver.config.AuthIntegrationConfig.java

/**
 * Ingoing message flow/*from ww  w  .  j av a  2  s .com*/
 *
 * @return - complete message transformation flow
 */
@Bean
public IntegrationFlow recvFlow() {
    return IntegrationFlows.from(tcpInputChannel()).transform(encoder, "decrypt")
            .transform(byte[].class, b -> wrappedBuffer(b).order(ByteOrder.LITTLE_ENDIAN))
            .transform(ByteBuf.class, encoder::validateChecksum).transform(clientPacketHandler, "handle")
            .channel(incomingPacketExecutorChannel()).get();
}

From source file:au.org.ala.delta.io.BinFile.java

public void writeInts(int[] values) {
    ByteBuffer b = ByteBuffer.allocate(values.length * 4);
    b.order(ByteOrder.LITTLE_ENDIAN);
    for (int value : values) {
        b.putInt(value);/*  w ww.  j  av  a2 s  . c o  m*/
    }
    writeBytes(b);
}

From source file:com.DorsetEggs.waver.communicatorService.java

public static byte[] toByteArray(KeyframePacket obj) throws IOException {
    ByteBuffer bytes = ByteBuffer.allocate(4);
    bytes.order(ByteOrder.LITTLE_ENDIAN);
    bytes.put(obj.servoToApplyTo);//from w w w . j a  v  a 2 s.c o  m
    bytes.put(obj.degreesToReach);
    bytes.putShort(obj.timeToPosition);
    return bytes.array();
}

From source file:au.org.ala.delta.io.BinFile.java

public void writeLong(long value) {
    ByteBuffer b = ByteBuffer.allocate(8);
    b.order(ByteOrder.LITTLE_ENDIAN);
    b.putLong(value);
    writeBytes(b);
}

From source file:org.openpilot_nonag.uavtalk.UAVTalk.java

/**
 * Constructor/* w ww  . j a v a2 s  .c o m*/
 */
public UAVTalk(InputStream inStream, OutputStream outStream, UAVObjectManager objMngr) {
    this.objMngr = objMngr;
    this.inStream = inStream;
    this.outStream = outStream;

    rxState = RxStateType.STATE_SYNC;
    rxPacketLength = 0;

    // mutex = new QMutex(QMutex::Recursive);

    resetStats();
    rxTmpBuffer = ByteBuffer.allocate(4);
    rxTmpBuffer.order(ByteOrder.LITTLE_ENDIAN);
    rxBuffer = ByteBuffer.allocate(MAX_PAYLOAD_LENGTH);
    rxBuffer.order(ByteOrder.LITTLE_ENDIAN);

    // TOOD: Callback connect(io, SIGNAL(readyRead()), this,
    // SLOT(processInputStream()));

    event = 0;
    String fileName = new SimpleDateFormat("'data/opuavo-'yyyyMMddhhmm'.txt'").format(new Date());
    dataOutFile = new File(fileName);
}

From source file:nodomain.freeyourgadget.gadgetbridge.devices.pebble.PBWReader.java

public PBWReader(Uri uri, Context context, String platform) throws IOException {
    uriHelper = UriHelper.get(uri, context);

    if (uriHelper.getFileName().endsWith(".pbl")) {
        STM32CRC stm32crc = new STM32CRC();
        try (InputStream fin = uriHelper.openInputStream()) {
            byte[] buf = new byte[2000];
            while (fin.available() > 0) {
                int count = fin.read(buf);
                stm32crc.addData(buf, count);
            }//from  w w  w. ja  v  a 2  s  .  co m
        }
        int crc = stm32crc.getResult();
        // language file
        app = new GBDeviceApp(UUID.randomUUID(), "Language File", "unknown", "unknown",
                GBDeviceApp.Type.UNKNOWN);
        pebbleInstallables = new ArrayList<>();
        pebbleInstallables.add(new PebbleInstallable("lang", (int) uriHelper.getFileSize(), crc,
                PebbleProtocol.PUTBYTES_TYPE_FILE));

        isValid = true;
        isLanguage = true;
        return;
    }

    String platformDir = "";
    if (!uriHelper.getFileName().endsWith(".pbz")) {
        platformDir = determinePlatformDir(uriHelper, platform);

        if (platform.equals("chalk") && platformDir.equals("")) {
            return;
        }
    }

    LOG.info("using platformdir: '" + platformDir + "'");
    String appName = null;
    String appCreator = null;
    String appVersion = null;
    UUID appUUID = null;

    ZipEntry ze;
    pebbleInstallables = new ArrayList<>();
    byte[] buffer = new byte[1024];
    int count;
    try (ZipInputStream zis = new ZipInputStream(uriHelper.openInputStream())) {
        while ((ze = zis.getNextEntry()) != null) {
            String fileName = ze.getName();
            if (fileName.equals(platformDir + "manifest.json")) {
                long bytes = ze.getSize();
                if (bytes > 8192) // that should be too much
                    break;

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((count = zis.read(buffer)) != -1) {
                    baos.write(buffer, 0, count);
                }

                String jsonString = baos.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    HashMap<String, Byte> fileTypeMap;

                    try {
                        JSONObject firmware = json.getJSONObject("firmware");
                        fileTypeMap = fwFileTypesMap;
                        isFirmware = true;
                        hwRevision = firmware.getString("hwrev");
                    } catch (JSONException e) {
                        fileTypeMap = appFileTypesMap;
                        isFirmware = false;
                    }
                    for (Map.Entry<String, Byte> entry : fileTypeMap.entrySet()) {
                        try {
                            JSONObject jo = json.getJSONObject(entry.getKey());
                            String name = jo.getString("name");
                            int size = jo.getInt("size");
                            long crc = jo.getLong("crc");
                            byte type = entry.getValue();
                            pebbleInstallables
                                    .add(new PebbleInstallable(platformDir + name, size, (int) crc, type));
                            LOG.info("found file to install: " + platformDir + name);
                            isValid = true;
                        } catch (JSONException e) {
                            // not fatal
                        }
                    }
                } catch (JSONException e) {
                    // no JSON at all that is a problem
                    isValid = false;
                    e.printStackTrace();
                    break;
                }

            } else if (fileName.equals("appinfo.json")) {
                long bytes = ze.getSize();
                if (bytes > 500000) {
                    LOG.warn(fileName + " exeeds maximum of 500000 bytes");
                    // that should be too much
                    break;
                }

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                while ((count = zis.read(buffer)) != -1) {
                    baos.write(buffer, 0, count);
                }

                String jsonString = baos.toString();
                try {
                    JSONObject json = new JSONObject(jsonString);
                    appName = json.getString("shortName");
                    appCreator = json.getString("companyName");
                    appVersion = json.getString("versionLabel");
                    appUUID = UUID.fromString(json.getString("uuid"));
                    if (json.has("appKeys")) {
                        mAppKeys = json.getJSONObject("appKeys");
                        LOG.info("found appKeys:" + mAppKeys.toString());
                    }
                } catch (JSONException e) {
                    isValid = false;
                    e.printStackTrace();
                    break;
                }
            } else if (fileName.equals(platformDir + "pebble-app.bin")) {
                zis.read(buffer, 0, 108);
                byte[] tmp_buf = new byte[32];
                ByteBuffer buf = ByteBuffer.wrap(buffer);
                buf.order(ByteOrder.LITTLE_ENDIAN);
                buf.getLong(); // header, TODO: verify
                buf.getShort(); // struct version, TODO: verify
                mSdkVersion = buf.getShort();
                mAppVersion = buf.getShort();
                buf.getShort(); // size
                buf.getInt(); // offset
                buf.getInt(); // crc
                buf.get(tmp_buf, 0, 32); // app name
                buf.get(tmp_buf, 0, 32); // author
                mIconId = buf.getInt();
                LOG.info("got icon id from pebble-app.bin: " + mIconId);
                buf.getInt(); // symbol table addr
                mFlags = buf.getInt();
                LOG.info("got flags from pebble-app.bin: " + mFlags);
                // more follows but, not interesting for us
            }
        }
        if (appUUID != null && appName != null && appCreator != null && appVersion != null) {
            GBDeviceApp.Type appType = GBDeviceApp.Type.APP_GENERIC;

            if ((mFlags & 16) == 16) {
                appType = GBDeviceApp.Type.APP_ACTIVITYTRACKER;
            } else if ((mFlags & 1) == 1) {
                appType = GBDeviceApp.Type.WATCHFACE;
            }
            app = new GBDeviceApp(appUUID, appName, appCreator, appVersion, appType);
        } else if (!isFirmware) {
            isValid = false;
        }
    }
}

From source file:org.bimserver.collada.SupportFunctions.java

public static void printMatrix(PrintWriter out, GeometryInfo geometryInfo) {
    ByteBuffer transformation = ByteBuffer.wrap(geometryInfo.getTransformation());
    transformation.order(ByteOrder.LITTLE_ENDIAN);
    FloatBuffer floatBuffer = transformation.asFloatBuffer();
    // Prepare to create the transform matrix.
    float[] matrix = new float[16];
    // Add the first 16 values of the buffer.
    for (int i = 0; i < matrix.length; i++)
        matrix[i] = floatBuffer.get();//from   w w  w  .java2  s . c  o  m
    // Switch from column-major (x.x ... x.y ... x.z ... 0 ...) to row-major orientation (x.x x.y x.z 0 ...)?
    matrix = Matrix.changeOrientation(matrix);
    // List all 16 elements of the matrix as a single space-delimited String object.
    if (!matrix.equals(identity))
        out.println("    <matrix>" + floatArrayToSpaceDelimitedString(matrix) + "</matrix>");
}

From source file:ome.io.nio.PixelsService.java

private PixelsPyramidMinMaxStore performWrite(final Pixels pixels, final File pixelsPyramidFile,
        final BfPyramidPixelBuffer pixelsPyramid, final File pixelsFile, final String pixelsFilePath,
        final String originalFilePath) {

    final PixelBuffer source;
    final Dimension tileSize;
    final PixelsPyramidMinMaxStore minMaxStore;

    if (pixelsFile.exists()) {
        minMaxStore = null;/*from  w  w  w.j a  v  a 2 s .  c o  m*/
        source = createRomioPixelBuffer(pixelsFilePath, pixels, false);
        // FIXME: This should be configuration or service driven
        // FIXME: Also implemented in RenderingBean.getTileSize()
        tileSize = new Dimension(Math.min(pixels.getSizeX(), sizes.getTileWidth()),
                Math.min(pixels.getSizeY(), sizes.getTileHeight()));
    } else {
        minMaxStore = new PixelsPyramidMinMaxStore(pixels.getSizeC());
        int series = getSeries(pixels);
        BfPixelBuffer bfPixelBuffer = createMinMaxBfPixelBuffer(originalFilePath, series, minMaxStore);
        pixelsPyramid
                .setByteOrder(bfPixelBuffer.isLittleEndian() ? ByteOrder.LITTLE_ENDIAN : ByteOrder.BIG_ENDIAN);
        source = bfPixelBuffer;
        // If the tile sizes we've been given are completely ridiculous
        // then reset them to WIDTHxHEIGHT. Currently these conditions are:
        //  * TileWidth == ImageWidth
        //  * TileHeight == ImageHeight
        //  * Smallest tile dimension divided by the largest resolution
        //    level factor is < 1.
        // -- Chris Allan (ome:#5224).
        final Dimension sourceTileSize = source.getTileSize();
        final double tileWidth = sourceTileSize.getWidth();
        final double tileHeight = sourceTileSize.getHeight();
        final boolean tileDimensionTooSmall;
        double factor = Math.pow(2, 5);
        if (((tileWidth / factor) < 1.0) || ((tileHeight / factor) < 1.0)) {
            tileDimensionTooSmall = true;
        } else {
            tileDimensionTooSmall = false;
        }
        if (tileWidth == source.getSizeX() || tileHeight == source.getSizeY() || tileDimensionTooSmall) {
            tileSize = new Dimension(Math.min(pixels.getSizeX(), sizes.getTileWidth()),
                    Math.min(pixels.getSizeY(), sizes.getTileHeight()));
        } else {
            tileSize = sourceTileSize;
        }
    }
    log.info("Destination pyramid tile size: " + tileSize);

    try {
        final double totalTiles = source.getSizeZ() * source.getSizeC() * source.getSizeT()
                * (Math.ceil(source.getSizeX() / tileSize.getWidth()))
                * (Math.ceil(source.getSizeY() / tileSize.getHeight()));
        final int tenPercent = Math.max((int) totalTiles / 10, 1);
        Utils.forEachTile(new TileLoopIteration() {
            public void run(int z, int c, int t, int x, int y, int w, int h, int tileCount) {
                if (log.isInfoEnabled() && tileCount % tenPercent == 0) {
                    log.info(String.format("Pyramid creation for Pixels:%d %d/%d (%d%%).", pixels.getId(),
                            tileCount + 1, (int) totalTiles, (int) (tileCount / totalTiles * 100)));
                }
                try {
                    PixelData tile = source.getTile(z, c, t, x, y, w, h);
                    pixelsPyramid.setTile(tile.getData().array(), z, c, t, x, y, w, h);
                } catch (IOException e1) {
                    log.error("FAIL -- Error during tile population", e1);
                    try {
                        pixelsPyramidFile.delete();
                        FileUtils.touch(pixelsPyramidFile); // ticket:5189
                    } catch (Exception e2) {
                        log.warn("Error clearing empty or incomplete pixel " + "buffer.", e2);
                    }
                    return;
                }
            }
        }, source, (int) tileSize.getWidth(), (int) tileSize.getHeight());

        log.info("SUCCESS -- Pyramid created for pixels id:" + pixels.getId());

    }

    finally {
        if (source != null) {
            try {
                source.close();
            } catch (IOException e) {
                log.error("Error closing pixel pyramid.", e);
            }
        }
    }
    return minMaxStore;
}

From source file:com.tesora.dve.db.mysql.DBTypeBasedUtilsTest.java

@Test
public void mysqlConvertTest() throws Exception {
    ByteBuf cb;/*w  ww .  jav a 2  s  . c om*/

    ListOfPairs<MyFieldType, Object> expValuesConvMysql = new ListOfPairs<MyFieldType, Object>();
    expValuesConvMysql.add(new Pair<MyFieldType, Object>(MyFieldType.FIELD_TYPE_LONG, new Integer(8765432)));
    expValuesConvMysql.add(new Pair<MyFieldType, Object>(MyFieldType.FIELD_TYPE_LONGLONG, new Long(8765432)));
    expValuesConvMysql
            .add(new Pair<MyFieldType, Object>(MyFieldType.FIELD_TYPE_SHORT, new Short((short) 5678)));
    expValuesConvMysql.add(new Pair<MyFieldType, Object>(MyFieldType.FIELD_TYPE_TINY, new Integer(100)));
    expValuesConvMysql.add(new Pair<MyFieldType, Object>(MyFieldType.FIELD_TYPE_TINY, new Byte((byte) 1)));
    //      expValuesConvMysql.add(new Pair<MyFieldType, Object>(MyFieldType.FIELD_TYPE_BIT, new Boolean(true)));

    int len;
    for (Pair<MyFieldType, Object> expValue : expValuesConvMysql) {
        len = 0;
        if (expValue.getSecond() instanceof Byte)
            len = 1;

        cb = Unpooled.buffer(100).order(ByteOrder.LITTLE_ENDIAN);
        DataTypeValueFunc dtvf = DBTypeBasedUtils.getMysqlTypeFunc(expValue.getFirst(), len, 0);
        dtvf.writeObject(cb, expValue.getSecond());
        assertEquals(expValue.getSecond(), dtvf.readObject(cb));
    }

}

From source file:org.helios.jzab.agent.logging.ZabbixLoggingHandler.java

/**
 * Decodes the little endian encoded bytes to a long
 * @param bytes The bytes to decode//from  www  .  jav  a 2  s  .  c om
 * @return the decoded long value
 */
public static long decodeLittleEndianLongBytes(byte[] bytes) {
    return ((ByteBuffer) ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN).put(bytes).flip()).getLong();
}