Example usage for java.nio ByteBuffer asIntBuffer

List of usage examples for java.nio ByteBuffer asIntBuffer

Introduction

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

Prototype

public abstract IntBuffer asIntBuffer();

Source Link

Document

Returns a int buffer which is based on the remaining content of this byte buffer.

Usage

From source file:org.lenskit.data.packed.BinaryIndexTable.java

/**
 * Create a binary index table./*from  w  w w  . j ava 2  s  . co  m*/
 * @param nentries The number of entries in the table.
 * @param buffer The table buffer.  Its position will be advanced to the end of the table.
 * @return The index table.
 */
public static BinaryIndexTable fromBuffer(int nentries, ByteBuffer buffer) {
    logger.debug("reading table of {} entries", nentries);
    long[] keys = new long[nentries];
    int[] offsets = new int[nentries];
    int[] sizes = new int[nentries];
    // Read the index table's header (IDs, offsets, and counts/sizes).
    int nextExpectedOffset = 0;
    for (int i = 0; i < nentries; i++) {
        keys[i] = buffer.getLong();
        if (i > 0 && keys[i - 1] >= keys[i]) {
            logger.error("key {} is not greater than previous key {}", keys[i], keys[i - 1]);
            throw new IllegalArgumentException("corrupted index table");
        }
        offsets[i] = buffer.getInt();
        sizes[i] = buffer.getInt();
        if (offsets[i] != nextExpectedOffset) {
            logger.error("expected offset {}, got {}", nextExpectedOffset, offsets[i]);
            throw new IllegalArgumentException("corrupted index table");
        }
        nextExpectedOffset += sizes[i];
    }

    // Set up the integer store
    if (buffer.remaining() < nextExpectedOffset * 4) {
        throw new IllegalArgumentException("buffer not large enough");
    }
    int end = buffer.position() + nextExpectedOffset * 4;
    ByteBuffer dup = buffer.duplicate();
    dup.limit(end);
    // update input indexStore's position
    buffer.position(end);
    // create index table object
    LongKeyDomain dom = LongKeyDomain.wrap(keys, keys.length, true);
    return new BinaryIndexTable(dom, offsets, sizes, dup.asIntBuffer());
}

From source file:info.varden.anatychia.Main.java

public static MaterialDataList materialList(SaveData save, ProgressUpdater pu, MaterialData[] filters) {
    Random random = new Random();
    boolean filtersNull = filters == null;
    pu.updated(0, 1);//from  w ww.  ja v  a 2s  .  c  o m
    pu.updated(-3, 1);
    MaterialDataList mdl = new MaterialDataList();
    File saveDir = save.getLocation();
    File[] regionFolders = listRegionContainers(saveDir);
    int depth = Integer.MAX_VALUE;
    File shallowest = null;
    for (File f : regionFolders) {
        String path = f.getAbsolutePath();
        Pattern p = Pattern.compile(Pattern.quote(File.separator));
        Matcher m = p.matcher(path);
        int count = 0;
        while (m.find()) {
            count++;
        }
        if (count < depth) {
            depth = count;
            if (shallowest == null || f.getName().equalsIgnoreCase("region")) {
                shallowest = f;
            }
        }
    }
    pu.updated(-1, 1);
    ArrayList<File> regions = new ArrayList<File>();
    int tfs = 0;
    for (File f : regionFolders) {
        String dimName = f.getParentFile().getName();
        boolean deleted = false;
        if (f.equals(shallowest)) {
            dimName = "DIM0";
        }
        if (!filtersNull) {
            for (MaterialData type : filters) {
                if (type.getType() == MaterialType.DIMENSION && type.getName().equals(dimName)) {
                    System.out.println("Deleting: " + dimName);
                    deleted = recursiveDelete(f);
                }
            }
        }
        if (deleted)
            continue;
        mdl.increment(new MaterialData(MaterialType.DIMENSION, dimName, 1L));
        File[] r = f.listFiles(new FilenameFilter() {

            @Override
            public boolean accept(File dir, String name) {
                return name.endsWith(".mca");
            }

        });
        int max = r.length;
        int cur = 0;
        for (File valid : r) {
            cur++;
            try {
                BufferedInputStream bis = new BufferedInputStream(new FileInputStream(valid));
                byte[] offsetHeader = new byte[4096];
                bis.read(offsetHeader, 0, 4096);
                bis.close();
                ByteBuffer bb = ByteBuffer.wrap(offsetHeader);
                IntBuffer ib = bb.asIntBuffer();
                while (ib.remaining() > 0) {
                    if (ib.get() != 0) {
                        tfs++;
                    }
                }
                bb = null;
                ib = null;
            } catch (IOException ex) {
                Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
            }
            // tfs += Math.floor(valid.length() / 1000D);
            pu.updated(cur, max);
        }
        regions.addAll(Arrays.asList(r));
    }
    if (regions.size() <= 0) {
        pu.updated(1, 1);
        return mdl;
    }
    pu.updated(-2, 1);
    int fc = 0;
    int fs = 0;
    for (File region : regions) {
        fc++;
        //fs += Math.floor(region.length() / 1000D);
        try {
            RegionFile anvil = new RegionFile(region);
            for (int x = 0; x < 32; x++) {
                for (int z = 0; z < 32; z++) {
                    InputStream is = anvil.getChunkDataInputStream(x, z);
                    if (is == null)
                        continue;
                    NBTInputStream nbti = new NBTInputStream(is, CompressionMode.NONE);
                    CompoundTag root = (CompoundTag) nbti.readTag();
                    String rootName = root.getName();
                    CompoundTag level = (CompoundTag) root.getValue().get("Level");
                    Map<String, Tag> levelTags = level.getValue();
                    ListTag sectionTag = (ListTag) levelTags.get("Sections");
                    ArrayList<Tag> sections = new ArrayList<Tag>(sectionTag.getValue());
                    for (int i = 0; i < sections.size(); i++) {
                        mdl.setSectorsRelative(1);
                        CompoundTag sect = (CompoundTag) sections.get(i);
                        Map<String, Tag> sectTags = sect.getValue();
                        ByteArrayTag blockArray = (ByteArrayTag) sectTags.get("Blocks");
                        byte[] add = new byte[0];
                        boolean hasAdd = false;
                        if (sectTags.containsKey("Add")) {
                            hasAdd = true;
                            ByteArrayTag addArray = (ByteArrayTag) sectTags.get("Add");
                            add = addArray.getValue();
                        }
                        byte[] blocks = blockArray.getValue();
                        for (int j = 0; j < blocks.length; j++) {
                            short id;
                            byte aid = (byte) 0;
                            if (hasAdd) {
                                aid = ChunkFormat.Nibble4(add, j);
                                id = (short) ((blocks[j] & 0xFF) + (aid << 8));
                            } else {
                                id = (short) (blocks[j] & 0xFF);
                            }
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.BLOCK
                                            && type.getName().equals(String.valueOf(blocks[j] & 0xFF))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        blocks[j] = (byte) 0;
                                        if (aid != 0) {
                                            add[j / 2] = (byte) (add[j / 2] & (j % 2 == 0 ? 0xF0 : 0x0F));
                                        }
                                        id = (short) 0;
                                    }
                                }
                            }
                            mdl.increment(new MaterialData(MaterialType.BLOCK, String.valueOf(id), 1L));
                        }
                        if (!filtersNull) {
                            HashMap<String, Tag> rSectTags = new HashMap<String, Tag>();
                            rSectTags.putAll(sectTags);
                            ByteArrayTag bat = new ByteArrayTag("Blocks", blocks);
                            rSectTags.put("Blocks", bat);
                            if (hasAdd) {
                                ByteArrayTag adt = new ByteArrayTag("Add", add);
                                rSectTags.put("Add", adt);
                            }
                            CompoundTag rSect = new CompoundTag(sect.getName(), rSectTags);
                            sections.set(i, rSect);
                        }
                    }
                    ListTag entitiesTag = (ListTag) levelTags.get("Entities");
                    ArrayList<Tag> entities = new ArrayList<Tag>(entitiesTag.getValue());
                    for (int i = entities.size() - 1; i >= 0; i--) {
                        CompoundTag entity = (CompoundTag) entities.get(i);
                        Map<String, Tag> entityTags = entity.getValue();
                        if (entityTags.containsKey("id")) {
                            StringTag idTag = (StringTag) entityTags.get("id");
                            String id = idTag.getValue();
                            boolean removed = false;
                            if (!filtersNull) {
                                for (MaterialData type : filters) {
                                    if (type.getType() == MaterialType.ENTITY
                                            && (type.getName().equals(id) || type.getName().equals(""))
                                            && (type.getRemovalChance() == 1D
                                                    || random.nextDouble() < type.getRemovalChance())) {
                                        if (type.fulfillsRequirements(entity)) {
                                            entities.remove(i);
                                            removed = true;
                                        }
                                    }
                                }
                            }
                            if (!removed) {
                                mdl.increment(new MaterialData(MaterialType.ENTITY, id, 1L));
                            }
                        }
                    }
                    nbti.close();
                    is.close();
                    if (!filtersNull) {
                        HashMap<String, Tag> rLevelTags = new HashMap<String, Tag>();
                        rLevelTags.putAll(levelTags);
                        ListTag rSectionTag = new ListTag("Sections", CompoundTag.class, sections);
                        rLevelTags.put("Sections", rSectionTag);
                        ListTag rEntityTag = new ListTag("Entities", CompoundTag.class, entities);
                        rLevelTags.put("Entities", rEntityTag);
                        final CompoundTag rLevel = new CompoundTag("Level", rLevelTags);
                        HashMap<String, Tag> rRootTags = new HashMap<String, Tag>() {
                            {
                                put("Level", rLevel);
                            }
                        };
                        CompoundTag rRoot = new CompoundTag(rootName, rRootTags);
                        OutputStream os = anvil.getChunkDataOutputStream(x, z);
                        NBTOutputStream nbto = new NBTOutputStream(os, CompressionMode.NONE);
                        nbto.writeTag(rRoot);
                        nbto.close();
                    }
                    fs++;
                    pu.updated(fs, tfs);
                }
            }
            anvil.close();
        } catch (Exception ex) {
            Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
    MaterialData[] data = mdl.toArray();
    System.out.println("FILES SCANNED: " + fc);
    for (MaterialData d : data) {
        System.out.println(d.getType().getName() + ": " + d.getName() + " (" + d.getQuantity() + ")");
    }
    return mdl;
}

From source file:VASSAL.tools.image.tilecache.TileUtils.java

/**
 * Write a tile image to a stream./*w  ww .  j  av  a 2  s.c o m*/
 *
 * @param tile the image
 * @param out the stream
 *
 * @throws ImageIOException if the write fails
 */
public static void write(BufferedImage tile, OutputStream out) throws IOException {
    ByteBuffer bb;

    // write the header
    bb = ByteBuffer.allocate(18);

    bb.put("VASSAL".getBytes()).putInt(tile.getWidth()).putInt(tile.getHeight()).putInt(tile.getType());

    out.write(bb.array());

    // write the tile data
    final DataBufferInt db = (DataBufferInt) tile.getRaster().getDataBuffer();
    final int[] data = db.getData();

    bb = ByteBuffer.allocate(4 * data.length);
    bb.asIntBuffer().put(data);

    final GZIPOutputStream zout = new GZIPOutputStream(out);
    zout.write(bb.array());
    zout.finish();
}

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

/**
 * Get histogram data/*from  w  w  w.  ja v a2  s  .  c o  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.hobbit.core.rabbit.FileStreamingTest.java

private void generateFiles(String sendInputDir) {
    System.out.println("Generating files...");
    if (!sendInputDir.endsWith(File.separator)) {
        sendInputDir += File.separator;
    }/*from  ww  w  .j a va 2s .c  om*/

    OutputStream os = null;
    // create first file
    try {
        os = new BufferedOutputStream(new FileOutputStream(sendInputDir + "file1.dat"));
        ByteBuffer buffer = ByteBuffer.allocate(4000);
        IntBuffer intBuffer = buffer.asIntBuffer();
        int number = 0;
        // for (int i = 0; i < 200; ++i) {
        for (int j = 0; j < 1000; ++j) {
            intBuffer.put(number);
            ++number;
        }
        os.write(buffer.array());
        buffer.position(0);
        intBuffer.position(0);
        // }
        os.flush();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        IOUtils.closeQuietly(os);
    }
    // create second file
    try {
        os = new BufferedOutputStream(new FileOutputStream(sendInputDir + "file2.txt"));
        byte data[] = "Lorem ipsum dolor sit amet, consectetur adipisici elit, sed eiusmod tempor incidunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquid ex ea commodi consequat. Quis aute iure reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint obcaecat cupiditat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
                .getBytes(Charsets.UTF_8);
        for (int i = 0; i < 200; ++i) {
            os.write(data);
        }
        os.flush();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        IOUtils.closeQuietly(os);
    }
    // create third file
    try {
        os = new BufferedOutputStream(new FileOutputStream(sendInputDir + "file3.dat"));
        ByteBuffer buffer = ByteBuffer.allocate(400);
        IntBuffer intBuffer = buffer.asIntBuffer();
        Random random = new Random();
        // for (int i = 0; i < 200; ++i) {
        for (int j = 0; j < 100; ++j) {
            intBuffer.put(random.nextInt());
        }
        os.write(buffer.array());
        buffer.position(0);
        intBuffer.position(0);
        // }
        os.flush();
    } catch (Exception e) {
        e.printStackTrace();
        Assert.fail();
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:org.mrgeo.data.raster.RasterWritable.java

private static byte[] rasterToBytes(final Raster raster) {
    final int datatype = raster.getTransferType();

    byte[] pixels;

    final Object elements = raster.getDataElements(raster.getMinX(), raster.getMinY(), raster.getWidth(),
            raster.getHeight(), null);//ww  w  .  j av  a 2  s  .com

    switch (datatype) {
    case DataBuffer.TYPE_BYTE: {
        pixels = (byte[]) elements;
        break;
    }
    case DataBuffer.TYPE_FLOAT: {
        final float[] floatElements = (float[]) elements;

        pixels = new byte[floatElements.length * RasterUtils.FLOAT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final FloatBuffer floatbuff = bytebuff.asFloatBuffer();
        floatbuff.put(floatElements);

        break;
    }
    case DataBuffer.TYPE_DOUBLE: {
        final double[] doubleElements = (double[]) elements;

        pixels = new byte[doubleElements.length * RasterUtils.DOUBLE_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final DoubleBuffer doubleBuff = bytebuff.asDoubleBuffer();
        doubleBuff.put(doubleElements);

        break;
    }
    case DataBuffer.TYPE_INT: {
        final int[] intElements = (int[]) elements;

        pixels = new byte[intElements.length * RasterUtils.INT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final IntBuffer intBuff = bytebuff.asIntBuffer();
        intBuff.put(intElements);

        break;
    }
    case DataBuffer.TYPE_SHORT:
    case DataBuffer.TYPE_USHORT: {
        final short[] shortElements = (short[]) elements;

        pixels = new byte[shortElements.length * RasterUtils.SHORT_BYTES];

        final ByteBuffer bytebuff = ByteBuffer.wrap(pixels);
        final ShortBuffer shortbuff = bytebuff.asShortBuffer();
        shortbuff.put(shortElements);

        break;
    }
    default:
        throw new RasterWritableException("Error trying to append raster.  Bad raster data type");
    }

    return pixels;
}

From source file:com.clov4r.moboplayer.android.nil.codec.SubtitleJni.java

public Bitmap createBitmapOfSubtitle(ByteBuffer data, int width, int height) {
    IntBuffer intBuffer = data.asIntBuffer();
    int[] dataArray = new int[intBuffer.limit()];
    intBuffer.get(dataArray);/*from  w  ww. j  ava2s .co m*/
    Bitmap rest = Bitmap.createBitmap(dataArray, width, height, Config.RGB_565);

    return rest;

}

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 };/*w  w w  .  j  a  va2s  .  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:com.atilika.kuromoji.trie.DoubleArrayTrie.java

public void write(OutputStream output) throws IOException {

    baseBuffer.rewind();/*from  w  w w . java2s .  c o  m*/
    checkBuffer.rewind();
    tailBuffer.rewind();

    int baseCheckSize = Math.min(maxBaseCheckIndex + 64, baseBuffer.capacity());
    int tailSize = Math.min(tailIndex - TAIL_OFFSET + 64, tailBuffer.capacity());

    DataOutputStream dataOutput = new DataOutputStream(new BufferedOutputStream(output));

    dataOutput.writeBoolean(compact);
    dataOutput.writeInt(baseCheckSize);
    dataOutput.writeInt(tailSize);

    WritableByteChannel channel = Channels.newChannel(dataOutput);

    ByteBuffer tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    IntBuffer tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(baseBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(baseCheckSize * 4);
    tmpIntBuffer = tmpBuffer.asIntBuffer();
    tmpIntBuffer.put(checkBuffer.array(), 0, baseCheckSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    tmpBuffer = ByteBuffer.allocate(tailSize * 2);
    CharBuffer tmpCharBuffer = tmpBuffer.asCharBuffer();
    tmpCharBuffer.put(tailBuffer.array(), 0, tailSize);
    tmpBuffer.rewind();
    channel.write(tmpBuffer);

    dataOutput.flush();
}

From source file:VASSAL.tools.image.tilecache.TileUtils.java

/**
 * Reads an image tile.//  w w  w.jav a 2s. c o m
 *
 * @param in a stream containing the tile data
 * @return the tile image
 *
 * @throws IOException if the read fails
 */
public static BufferedImage read(InputStream in) throws IOException {
    ByteBuffer bb;

    // read the header
    final byte[] header = readHeader(in);
    bb = ByteBuffer.wrap(header);

    // validate the signature
    final byte[] sig = new byte[6];
    bb.get(sig);
    checkSignature(sig);

    // get the dimensions and type
    final int w = bb.getInt();
    final int h = bb.getInt();
    final int type = bb.getInt();

    // read the image data
    final byte[] cdata = IOUtils.toByteArray(in);

    // decompress the image data
    InputStream zin = null;
    try {
        zin = new GZIPInputStream(new ByteArrayInputStream(cdata));
        bb = ByteBuffer.wrap(IOUtils.toByteArray(zin));
        zin.close();
    } finally {
        IOUtils.closeQuietly(zin);
    }

    // build the image
    final BufferedImage img = new BufferedImage(w, h, type);

    // FIXME: This might decelerate the image? If so, then we should
    // make a copy.
    final DataBufferInt db = (DataBufferInt) img.getRaster().getDataBuffer();
    final int[] data = db.getData();

    final IntBuffer ib = bb.asIntBuffer();
    ib.get(data);

    /*
        if (ib.hasRemaining()) {
          // buffer contains garbage at the end!
          throw new IOException("found " + (4*ib.remaining()) + " more bytes!");
        }
    */

    return img;
}