Example usage for com.google.common.io LittleEndianDataInputStream LittleEndianDataInputStream

List of usage examples for com.google.common.io LittleEndianDataInputStream LittleEndianDataInputStream

Introduction

In this page you can find the example usage for com.google.common.io LittleEndianDataInputStream LittleEndianDataInputStream.

Prototype

public LittleEndianDataInputStream(InputStream in) 

Source Link

Document

Creates a LittleEndianDataInputStream that wraps the given stream.

Usage

From source file:com.koda.persistence.rawfs.IOLoadThread.java

/**
 * Inits the./*from w  w w . j ava 2s.com*/
 *
 * @throws IOException Signals that an I/O exception has occurred.
 */
private void init() throws IOException {

    buffer = ByteBuffer.allocateDirect(4 * 4096);
    buffer.order(ByteOrder.nativeOrder());

    if (pl != null)
        pl.started();

    file = getLatestStoreFile();
    if (file == null) {
        LOG.warn("no saved caches found in :" + dataRoot + File.separator + " for cache [" + storeName + "]");
        //TODO
        if (pl != null)
            pl.finished();
        return;
    }
    fis = new FileInputStream(file);
    fileChannel = fis.getChannel();

    ByteOrder nativeByteOrder = ByteOrder.nativeOrder();
    boolean littleEndian = nativeByteOrder == ByteOrder.LITTLE_ENDIAN;
    if (littleEndian) {
        // Use Guava
        dis = new LittleEndianDataInputStream(fis);
    } else {
        // Use standard JDK java.io
        dis = new DataInputStream(fis);
    }

    int cfgSize = dis.readInt();
    buffer.clear();
    buffer.limit(cfgSize);
    int total = 0;
    // Read all bytes from channel till 'cfgSize' limit
    while ((total += fileChannel.read(buffer)) < cfgSize)
        ;

    buffer.flip();
    cfg = ExtCacheConfiguration.read(buffer, null);

    // Create cache instance first to make sure
    // that we set System property COMPRESSION_THRESHOLD
    //      try{
    //         cache = new OffHeapCache(cfg);
    //      }catch(Exception e){
    //         throw new IOException(e);
    //      }
}

From source file:terralib.World.java

@Override
protected void write(DataOutput output) throws IOException {
    ByteBuffer buffer = this.buffer.duplicate();
    DataInput input = new LittleEndianDataInputStream(new ByteBufferInputStream(buffer));

    // Header/*from  w ww. j av a2  s .co  m*/
    output.writeInt(VERSION);
    info.write(output);

    // Tiles
    buffer.position(tileBufferPos.get(0).intValue()); // Reset buffer

    Tile tempTile = new Tile();
    int nextMod = modifiedTiles.size() > 0 ? modifiedTiles.firstKey().intValue() : -1;
    for (int i = 0; i < info.getHeight() * info.getWidth(); i++) {
        if (nextMod == i) {
            modifiedTiles.get(Integer.valueOf(i)).write(output);
            modifiedTiles.remove(Integer.valueOf(i));
            nextMod = modifiedTiles.firstKey().intValue();

            skipTiles(input, 1);
            continue;
        }

        tempTile.parse(input);
        tempTile.write(output);
    }

    // Chests
    for (Entry<Position, Chest> entry : chests.entrySet()) {
        output.writeBoolean(true);

        entry.getKey().write(output);
        entry.getValue().write(output);
    }

    for (int i = 0; i < 1000 - chests.size(); i++) {
        output.writeBoolean(false);
    }

    // Signs
    for (Entry<Position, String> entry : signs.entrySet()) {
        output.writeBoolean(true);

        CSharpData.writeString(output, entry.getValue());
        entry.getKey().write(output);
    }

    for (int i = 0; i < 1000 - signs.size(); i++) {
        output.writeBoolean(false);
    }

    // NPCs
    for (Entry<Position, NPC> entry : npcs.entrySet()) {
        output.writeBoolean(true);

        entry.getValue().write(output);
        entry.getKey().write(output);
    }

    output.writeBoolean(false);
}

From source file:org.linguafranca.pwdb.kdbx.KdbxSerializer.java

private static void checkStartBytes(KdbxHeader kdbxHeader, InputStream decryptedInputStream)
        throws IOException {
    LittleEndianDataInputStream ledis = new LittleEndianDataInputStream(decryptedInputStream);

    byte[] startBytes = new byte[32];
    ledis.readFully(startBytes);//from   ww  w  .  j av a2  s.  c  o m
    if (!Arrays.equals(startBytes, kdbxHeader.getStreamStartBytes())) {
        throw new IllegalStateException("Inconsistent stream bytes");
    }
}

From source file:org.necsave.MraJsonExporter.java

private boolean processUamFrame(UamRxFrame msg, BufferedWriter writer, Gson gson) throws IOException {
    AcousticMessage acMsg = new AcousticMessage();
    byte[] data = msg.getData();
    ByteBuffer buf = ByteBuffer.wrap(data);
    buf.order(ByteOrder.LITTLE_ENDIAN);
    int sync = buf.getShort() & 0xFFFF;
    if (sync != 0xDE40)
        return false;

    String type = ProtoDefinition.getInstance().getMessageName(buf.getShort() & 0xFFFF);
    if (type == null)
        return false;

    Message m = ProtoDefinition.getFactory().createMessage(type, ProtoDefinition.getInstance());
    LittleEndianDataInputStream dis = new LittleEndianDataInputStream(
            new ByteArrayInputStream(data, 4, data.length - 4));
    ProtoDefinition.getInstance().deserializeFields(m, dis);

    acMsg.source = msg.getSysSrc();//from   w  w w.j av  a  2  s .c o m
    acMsg.destination = msg.getSysDst();
    acMsg.size = msg.getData().length;
    acMsg.receiveTime = msg.getTimestamp();

    if (m instanceof PlatformState) {
        PlatformState platfState = (PlatformState) m;
        acMsg.sendTime = platfState.getOriginTimestamp();
        acMsg.depth = platfState.getZ();
        acMsg.lat = Math.toDegrees(platfState.getLatitude());
        acMsg.lon = Math.toDegrees(platfState.getLongitude());
        acMsg.state = platfState.getInteger("state");
        acMsg.plan_version = platfState.getPlanVersion();
        System.out.println(gson.toJson(acMsg));
        if (!first)
            writer.write(",\n");
        first = false;
        writer.write(gson.toJson(acMsg));
    } else {
        System.out.println(m);
    }
    return true;
}

From source file:org.linguafranca.pwdb.kdbx.stream_3_1.KdbxSerializer.java

private static void checkStartBytes(KdbxHeader kdbxHeader, InputStream decryptedInputStream)
        throws IOException {
    LittleEndianDataInputStream ledis = new LittleEndianDataInputStream(decryptedInputStream);

    byte[] startBytes = new byte[32];
    ledis.readFully(startBytes);/*from   www .  j  a va 2  s .c o  m*/
    if (!Arrays.equals(startBytes, kdbxHeader.getStreamStartBytes())) {
        throw new IllegalStateException(
                "Inconsistent stream start bytes. This usually means the credentials were wromng.");
    }
}

From source file:de.johni0702.sponge.noteblockapi.impl.NBSongParser.java

@Override
public Song parseNBS(InputStream inputStream) throws IOException {

    DataInput in = new LittleEndianDataInputStream(inputStream);

    // Header/* w w  w  . j a v a 2  s .  com*/
    int length = in.readShort();
    int height = in.readShort();
    String name = readString(in);
    String author = readString(in);
    String originalAuthor = readString(in);
    String description = readString(in);
    double tempo = in.readShort() / 100d;
    in.skipBytes(23); // Skip unnecessary info
    in.skipBytes(in.readInt());

    // Note blocks
    Layer[] layers = new Layer[height];
    for (int i = 0; i < layers.length; i++) {
        layers[i] = new Layer();
    }

    int jump;
    int tick = -1;
    while ((jump = in.readShort()) != 0) {
        tick += jump;
        int layer = -1;
        while ((jump = in.readShort()) != 0) {
            layer += jump;

            Instrument instrument = Instrument.forId(in.readByte());
            NotePitch pitch = notePitchForId(gameRegistry, (in.readByte() - 33) % 24);

            layers[layer].setNoteBlock(tick, new NoteBlock(instrument, pitch));
        }
    }

    // Layer info
    for (Layer layer : layers) {
        layer.setName(readString(in));
        layer.setVolume(in.readByte() / 100d);
    }

    Song song = new Song(length, name, author, originalAuthor, description, tempo);
    song.getLayers().addAll(Arrays.asList(layers));
    return song;
}

From source file:org.esa.nest.gpf.ReadRatFileOp.java

/**
 * Called by the framework in order to compute a tile for the given target band.
 * <p>The default implementation throws a runtime exception with the message "not implemented".</p>
 *
 * @param targetTileMap   The target tiles associated with all target bands to be computed.
 * @param targetRectangle The rectangle of target tile.
 * @param pm              A progress monitor which should be used to determine computation cancelation requests.
 * @throws org.esa.beam.framework.gpf.OperatorException
 *          If an error occurs during computation of the target raster.
 *//*  w  w  w  . j  av a 2s .c  o m*/
@Override
public synchronized void computeTileStack(Map<Band, Tile> targetTileMap, Rectangle targetRectangle,
        ProgressMonitor pm) throws OperatorException {

    final int x0 = targetRectangle.x;
    final int y0 = targetRectangle.y;
    final int w = targetRectangle.width;
    final int h = targetRectangle.height;
    final int xMax = x0 + w;
    final int yMax = y0 + h;
    //System.out.println("x0 = " + x0 + ", y0 = " + y0 + ", w = " + w + ", h = " + h);

    final Band tgtBandI = targetProduct.getBand("i_band");
    final Band tgtBandQ = targetProduct.getBand("q_band");
    final Tile tgtTileI = targetTileMap.get(tgtBandI);
    final Tile tgtTileQ = targetTileMap.get(tgtBandQ);
    final ProductData tgtBufferI = tgtTileI.getDataBuffer();
    final ProductData tgtBufferQ = tgtTileQ.getDataBuffer();
    final TileIndex tgtIndex = new TileIndex(tgtTileI);

    try {
        LittleEndianDataInputStream in = new LittleEndianDataInputStream(
                new BufferedInputStream(new FileInputStream(ratFilePath)));
        in.skipBytes(1000 + y0 * width * 4 * 2);

        for (int y = y0; y < yMax; y++) {
            tgtIndex.calculateStride(y);
            for (int x = x0; x < xMax; x++) {
                final int tgtIdx = tgtIndex.getIndex(x);
                final float vI = in.readFloat();
                final float vQ = in.readFloat();
                tgtBufferI.setElemDoubleAt(tgtIdx, vI);
                tgtBufferQ.setElemDoubleAt(tgtIdx, vQ);
            }
        }

        in.close();

    } catch (Throwable e) {
        OperatorUtils.catchOperatorException("computeTileStack", e);
    }
}

From source file:terralib.World.java

public final Tile getTile(Position position) {
    checkArgument(info.getBounds().contains(position));

    Tile modified = modifiedTiles.get(Integer.valueOf(position.getX() * info.getHeight() + position.getY()));
    if (modified != null)
        return modified;

    try {/* ww  w  .j ava2 s .c om*/
        ByteBuffer buffer = this.buffer.duplicate();
        DataInput input = new LittleEndianDataInputStream(new ByteBufferInputStream(buffer));

        buffer.position(tileBufferPos.get(position.getX()).intValue());
        skipTiles(input, position.getY());
        return new Tile(input);
    } catch (IOException e) {
        throw new RuntimeException("Error reading tile");
    }
}

From source file:com.google.android.testing.nativedriver.client.FrameBufferFormat.java

/**
 * Copies the frame buffer data from an {@code InputStream] to a given
 * location in a {@code BufferedImage}.//from  ww w .jav  a 2s  . c  o m
 *
 * @param source the source to read the raw frame buffer data from. The format
 *        of the data should correspond to the format represented by this
 *        instance
 * @param destination the image to which to write the converted image data
 */
public void copyFrameBufferToImage(InputStream source, BufferedImage destination) {
    DataInput sourceDataStream = new LittleEndianDataInputStream(source);
    int[] oneLine = new int[getXResolution()];

    for (int y = 0; y < yResolution; y++) {
        convertToRgba32(sourceDataStream, oneLine);
        destination.setRGB(0, y, xResolution, 1, oneLine, 0, xResolution);
    }
}

From source file:terralib.World.java

public final TileGroup getTileGroup(Rectangle rect) {
    checkNotNull(rect);/*from w  w w  .j  av  a  2  s.c  o m*/

    try {
        ByteBuffer buffer = this.buffer.duplicate();
        DataInput input = new LittleEndianDataInputStream(new ByteBufferInputStream(buffer));

        Tile[] tileData = new Tile[rect.getWidth() * rect.getHeight()];
        int i = 0;

        for (int x = rect.getLeft(); x < rect.getRight(); x++) {
            buffer.position(tileBufferPos.get(x).intValue());
            skipTiles(input, rect.getTop());

            for (int y = rect.getTop(); y < rect.getBottom(); y++) {
                tileData[i++] = new Tile(input);
            }
        }

        return new TileGroup(rect, tileData);
    } catch (IOException e) {
        throw new RuntimeException("Error reading tiles");
    }
}