Java Code Examples for java.nio.ByteBuffer#order()

The following examples show how to use java.nio.ByteBuffer#order() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: SQLiteBlobHelper.java    From libcommon with Apache License 2.0 6 votes vote down vote up
/**
 * double[]をbyte[]に変換して返す
 *
 * @param array
 * @param offset
 * @param num
 * @return
 */
public static byte[] doubleArrayToByteArray(
	@NonNull final double[] array, final int offset, final int num) {
	
	final ByteBuffer buf = ByteBuffer.allocate(num * Double.SIZE / 8);
	buf.order(ByteOrder.nativeOrder());
	final int n8 = num % 8 + offset;
	final int n = offset + num;
	for (int i = offset; i < n8; i++) buf.putDouble(array[i]);
	for (int i = n8; i < n; i += 8) {
		buf.putDouble(array[i]);
		buf.putDouble(array[i + 1]);
		buf.putDouble(array[i + 2]);
		buf.putDouble(array[i + 3]);
		buf.putDouble(array[i + 4]);
		buf.putDouble(array[i + 5]);
		buf.putDouble(array[i + 6]);
		buf.putDouble(array[i + 7]);
	}
	buf.flip();
	return buf.array();
}
 
Example 2
Source File: Word2VecModel.java    From Word2VecJava with MIT License 6 votes vote down vote up
/**
 * Saves the model as a bin file that's compatible with the C version of Word2Vec
 */
public void toBinFile(final OutputStream out) throws IOException {
	final Charset cs = Charset.forName("UTF-8");
	final String header = String.format("%d %d\n", vocab.size(), layerSize);
	out.write(header.getBytes(cs));

	final double[] vector = new double[layerSize];
	final ByteBuffer buffer = ByteBuffer.allocate(4 * layerSize);
	buffer.order(ByteOrder.LITTLE_ENDIAN);	// The C version uses this byte order.
	for(int i = 0; i < vocab.size(); ++i) {
		out.write(String.format("%s ", vocab.get(i)).getBytes(cs));

		vectors.position(i * layerSize);
		vectors.get(vector);
		buffer.clear();
		for(int j = 0; j < layerSize; ++j)
			buffer.putFloat((float)vector[j]);
		out.write(buffer.array());

		out.write('\n');
	}

	out.flush();
}
 
Example 3
Source File: ShaderUtils.java    From jmonkeyengine with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static final ByteBuffer getImageDataFromImage(BufferedImage bufferedImage) {
	WritableRaster wr;
	DataBuffer db;

	BufferedImage bi = new BufferedImage(128, 64, BufferedImage.TYPE_INT_ARGB);
	Graphics2D g = bi.createGraphics();
	g.drawImage(bufferedImage, null, null);
	bufferedImage = bi;
	wr = bi.getRaster();
	db = wr.getDataBuffer();

	DataBufferInt dbi = (DataBufferInt) db;
	int[] data = dbi.getData();

	ByteBuffer byteBuffer = ByteBuffer.allocateDirect(data.length * 4);
	byteBuffer.order(ByteOrder.LITTLE_ENDIAN);
	byteBuffer.asIntBuffer().put(data);
	byteBuffer.flip();

	return byteBuffer;
}
 
Example 4
Source File: DoubleSerializer.java    From osmdroid with Apache License 2.0 5 votes vote down vote up
public static void serializeLittleEndian(final double value,
    final ByteBuffer b) {
  if (b == null) {
    throw new RuntimeException("Cannot serialize into a null byte buffer.");
  }
  if (b.array().length < BYTE_ARRAY_SIZE) {
    throw new RuntimeException(
        "Cannot serialize. Byte buffer must have at least " + BYTE_ARRAY_SIZE
            + " bytes.");
  }
  b.order(ByteOrder.LITTLE_ENDIAN);
  b.position(0);
  b.putDouble(value);
}
 
Example 5
Source File: LasWriterBuffered.java    From hortonmachine with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void close() throws Exception {
    // write leftover points
    if (runningBytesCount > 0) {
        writeMainBuffer(runningBytesCount);
        runningBytesCount = 0;
    }

    byte[] longDataArray = new byte[4];
    ByteBuffer longBb = ByteBuffer.wrap(longDataArray);
    longBb.order(ByteOrder.LITTLE_ENDIAN);
    byte[] shortDataArray = new byte[2];
    ByteBuffer shortBb = ByteBuffer.wrap(shortDataArray);
    shortBb.order(ByteOrder.LITTLE_ENDIAN);
    longBb.putInt(recordsNum);
    byte[] array = longBb.array();
    fileChannel.position(recordsNumPosition);
    fos.write(array);
    fileChannel.position(pointFormatPosition);
    fos.write(pointFormat);
    shortBb.putShort(recordLength);
    array = shortBb.array();
    fileChannel.position(recordLengthPosition);
    fos.write(array);

    closeFile();

    /*
     * write crs file
     */
    if (crs != null)
        CrsUtilities.writeProjectionFile(prjFile.getAbsolutePath(), null, crs);
}
 
Example 6
Source File: CompactInt.java    From bitshares_wallet with MIT License 5 votes vote down vote up
/**
 * Read a CompactInt from a byte buffer.
 * 
 * @param buf
 *           The byte buffer to read from
 * @return the long value representing the CompactInt read or -1 if the
 *         buffer is too small to hold the CompactInt.
 */
public static long fromByteBuffer(ByteBuffer buf) {
   if (buf.remaining() < 1) {
      // XXX make all callers check for -1
      return -1;
   }
   long first = 0x00000000000000FFL & ((long) buf.get());
   long value;
   if (first < 253) {
      // Regard this byte as a 8 bit value.
      value = 0x00000000000000FFL & ((long) first);
   } else if (first == 253) {
      // Regard the following two bytes as a 16 bit value
      if (buf.remaining() < 2) {
         return -1;
      }
      buf.order(ByteOrder.LITTLE_ENDIAN);
      value = 0x0000000000FFFFL & ((long) buf.getShort());
   } else if (first == 254) {
      // Regard the following four bytes as a 32 bit value
      if (buf.remaining() < 4) {
         return -1;
      }
      buf.order(ByteOrder.LITTLE_ENDIAN);
      value = 0x00000000FFFFFFFF & ((long) buf.getInt());
   } else {
      // Regard the following four bytes as a 64 bit value
      if (buf.remaining() < 8) {
         return -1;
      }
      buf.order(ByteOrder.LITTLE_ENDIAN);
      value = buf.getLong();
   }
   return value;
}
 
Example 7
Source File: RCONPacket.java    From Nukkit with GNU General Public License v3.0 5 votes vote down vote up
public ByteBuffer toBuffer() {
    ByteBuffer buffer = ByteBuffer.allocate(this.payload.length + 14);
    buffer.order(ByteOrder.LITTLE_ENDIAN);

    buffer.putInt(this.payload.length + 10);
    buffer.putInt(this.id);
    buffer.putInt(this.type);
    buffer.put(this.payload);

    buffer.put((byte) 0);
    buffer.put((byte) 0);

    buffer.flip();
    return buffer;
}
 
Example 8
Source File: PLUtils.java    From panoramagl with Apache License 2.0 5 votes vote down vote up
public static FloatBuffer makeFloatBuffer(int length) {
    final int floatSize = Float.SIZE / 8;
    ByteBuffer byteBuffer = ByteBuffer.allocateDirect(length * floatSize);
    byteBuffer.order(ByteOrder.nativeOrder());
    FloatBuffer floatBuffer = byteBuffer.asFloatBuffer();
    floatBuffer.position(0);
    return floatBuffer;
}
 
Example 9
Source File: FrameworkMediaDrm.java    From MediaSDK with Apache License 2.0 5 votes vote down vote up
/**
 * If the LA_URL tag is missing, injects a mock LA_URL value to avoid causing the CDM to throw
 * when creating the key request. The LA_URL attribute is optional but some Android PlayReady
 * implementations are known to require it. Does nothing it the provided {@code data} already
 * contains an LA_URL value.
 */
private static byte[] addLaUrlAttributeIfMissing(byte[] data) {
  ParsableByteArray byteArray = new ParsableByteArray(data);
  // See https://docs.microsoft.com/en-us/playready/specifications/specifications for more
  // information about the init data format.
  int length = byteArray.readLittleEndianInt();
  int objectRecordCount = byteArray.readLittleEndianShort();
  int recordType = byteArray.readLittleEndianShort();
  if (objectRecordCount != 1 || recordType != 1) {
    Log.i(TAG, "Unexpected record count or type. Skipping LA_URL workaround.");
    return data;
  }
  int recordLength = byteArray.readLittleEndianShort();
  String xml = byteArray.readString(recordLength, Charset.forName(C.UTF16LE_NAME));
  if (xml.contains("<LA_URL>")) {
    // LA_URL already present. Do nothing.
    return data;
  }
  // This PlayReady object record does not include an LA_URL. We add a mock value for it.
  int endOfDataTagIndex = xml.indexOf("</DATA>");
  if (endOfDataTagIndex == -1) {
    Log.w(TAG, "Could not find the </DATA> tag. Skipping LA_URL workaround.");
  }
  String xmlWithMockLaUrl =
      xml.substring(/* beginIndex= */ 0, /* endIndex= */ endOfDataTagIndex)
          + MOCK_LA_URL
          + xml.substring(/* beginIndex= */ endOfDataTagIndex);
  int extraBytes = MOCK_LA_URL.length() * UTF_16_BYTES_PER_CHARACTER;
  ByteBuffer newData = ByteBuffer.allocate(length + extraBytes);
  newData.order(ByteOrder.LITTLE_ENDIAN);
  newData.putInt(length + extraBytes);
  newData.putShort((short) objectRecordCount);
  newData.putShort((short) recordType);
  newData.putShort((short) (xmlWithMockLaUrl.length() * UTF_16_BYTES_PER_CHARACTER));
  newData.put(xmlWithMockLaUrl.getBytes(Charset.forName(C.UTF16LE_NAME)));
  return newData.array();
}
 
Example 10
Source File: MonitorThread.java    From javaide with GNU General Public License v3.0 5 votes vote down vote up
private void callHandler(Client client, JdwpPacket packet,
        ChunkHandler handler) {

    // on first DDM packet received, broadcast a "ready" message
    if (!client.ddmSeen())
        broadcast(CLIENT_READY, client);

    ByteBuffer buf = packet.getPayload();
    int type, length;
    boolean reply = true;

    type = buf.getInt();
    length = buf.getInt();

    if (handler == null) {
        // not a reply, figure out who wants it
        synchronized (mHandlerMap) {
            handler = mHandlerMap.get(type);
            reply = false;
        }
    }

    if (handler == null) {
        Log.w("ddms", "Received unsupported chunk type "
                + ChunkHandler.name(type) + " (len=" + length + ")");
    } else {
        Log.d("ddms", "Calling handler for " + ChunkHandler.name(type)
                + " [" + handler + "] (len=" + length + ")");
        ByteBuffer ibuf = buf.slice();
        ByteBuffer roBuf = ibuf.asReadOnlyBuffer(); // enforce R/O
        roBuf.order(ChunkHandler.CHUNK_ORDER);
        // do the handling of the chunk synchronized on the client list
        // to be sure there's no concurrency issue when we look for HOME
        // in hasApp()
        synchronized (mClientList) {
            handler.handleChunk(client, type, roBuf, reply, packet.getId());
        }
    }
}
 
Example 11
Source File: PointsMatrix.java    From MegviiFacepp-Android-SDK with Apache License 2.0 5 votes vote down vote up
public FloatBuffer floatBufferUtil(float[] arr) {
	// 初始化ByteBuffer,长度为arr数组的长度*4,因为一个int占4个字节
	ByteBuffer qbb = ByteBuffer.allocateDirect(arr.length * 4);
	// 数组排列用nativeOrder
	qbb.order(ByteOrder.nativeOrder());
	FloatBuffer mBuffer = qbb.asFloatBuffer();
	mBuffer.put(arr);
	mBuffer.position(0);
	return mBuffer;
}
 
Example 12
Source File: CameraViewModel.java    From VIA-AI with MIT License 5 votes vote down vote up
private void checkDataUpdate()
{
    if(mNeedUpdate) {
        // VBO update vertex coordinate
        ByteBuffer bb = ByteBuffer.allocateDirect(mPosition.length * 4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer vertexBuffer = bb.asFloatBuffer();
        vertexBuffer.put(mPosition);
        vertexBuffer.position(0);

        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, mPositionVBO[0]);
        GLUtility.checkGlError("glBindBuffer");

        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, mPosition.length * 4, vertexBuffer, GLES20.GL_STATIC_DRAW);
        GLUtility.checkGlError("glBufferData");


        // VBO update texture coordinate
        GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, mTextureCoordinateVBO[0]);
        GLUtility.checkGlError("glBindBuffer");

        bb = ByteBuffer.allocateDirect(mTextureCoordinate.length * 4);
        bb.order(ByteOrder.nativeOrder());
        FloatBuffer textureCoordinateBuffer = bb.asFloatBuffer();
        textureCoordinateBuffer.put(mTextureCoordinate);
        textureCoordinateBuffer.position(0);

        GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER, mTextureCoordinate.length * 4, textureCoordinateBuffer, GLES20.GL_STATIC_DRAW);
        GLUtility.checkGlError("glBufferData");

        mNeedUpdate = false;
    }
}
 
Example 13
Source File: ArrayDataPointerConstant.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public ArrayDataPointerConstant(double[] array, int alignment) {
    super(alignment);
    ByteBuffer byteBuffer = ByteBuffer.allocate(array.length * 8);
    byteBuffer.order(ByteOrder.nativeOrder());
    byteBuffer.asDoubleBuffer().put(array);
    data = byteBuffer.array();
}
 
Example 14
Source File: V2SchemeVerifier.java    From walle with Apache License 2.0 4 votes vote down vote up
/**
 * Verifies integrity of the APK outside of the APK Signing Block by computing digests of the
 * APK and comparing them against the digests listed in APK Signing Block. The expected digests
 * taken from {@code v2SchemeSignerInfos} of the provided {@code result}.
 */
private static void verifyIntegrity(
        DataSource beforeApkSigningBlock,
        DataSource centralDir,
        ByteBuffer eocd,
        Set<ContentDigestAlgorithm> contentDigestAlgorithms,
        Result result) throws IOException {
    if (contentDigestAlgorithms.isEmpty()) {
        // This should never occur because this method is invoked once at least one signature
        // is verified, meaning at least one content digest is known.
        throw new RuntimeException("No content digests found");
    }

    // For the purposes of verifying integrity, ZIP End of Central Directory (EoCD) must be
    // treated as though its Central Directory offset points to the start of APK Signing Block.
    // We thus modify the EoCD accordingly.
    ByteBuffer modifiedEocd = ByteBuffer.allocate(eocd.remaining());
    modifiedEocd.order(ByteOrder.LITTLE_ENDIAN);
    modifiedEocd.put(eocd);
    modifiedEocd.flip();
    ZipUtils.setZipEocdCentralDirectoryOffset(modifiedEocd, beforeApkSigningBlock.size());
    Map<ContentDigestAlgorithm, byte[]> actualContentDigests;
    try {
        actualContentDigests =
                V2SchemeSigner.computeContentDigests(
                        contentDigestAlgorithms,
                        new DataSource[] {
                                beforeApkSigningBlock,
                                centralDir,
                                new ByteBufferDataSource(modifiedEocd)
                        });
    } catch (DigestException e) {
        throw new RuntimeException("Failed to compute content digests", e);
    }
    if (!contentDigestAlgorithms.equals(actualContentDigests.keySet())) {
        throw new RuntimeException(
                "Mismatch between sets of requested and computed content digests"
                        + " . Requested: " + contentDigestAlgorithms
                        + ", computed: " + actualContentDigests.keySet());
    }

    // Compare digests computed over the rest of APK against the corresponding expected digests
    // in signer blocks.
    for (Result.SignerInfo signerInfo : result.signers) {
        for (Result.SignerInfo.ContentDigest expected : signerInfo.contentDigests) {
            SignatureAlgorithm signatureAlgorithm =
                    SignatureAlgorithm.findById(expected.getSignatureAlgorithmId());
            if (signatureAlgorithm == null) {
                continue;
            }
            ContentDigestAlgorithm contentDigestAlgorithm =
                    signatureAlgorithm.getContentDigestAlgorithm();
            byte[] expectedDigest = expected.getValue();
            byte[] actualDigest = actualContentDigests.get(contentDigestAlgorithm);
            if (!Arrays.equals(expectedDigest, actualDigest)) {
                signerInfo.addError(
                        Issue.V2_SIG_APK_DIGEST_DID_NOT_VERIFY,
                        contentDigestAlgorithm,
                        toHex(expectedDigest),
                        toHex(actualDigest));
                continue;
            }
            signerInfo.verifiedContentDigests.put(contentDigestAlgorithm, actualDigest);
        }
    }
}
 
Example 15
Source File: DDSConverter.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
public static ByteBuffer convertToDxt1NoTransparency(BufferedImage image) {
	if (image == null) {
		return null;
	}

	int[] pixels = new int[16];
	int bufferSize = 128 + image.getWidth() * image.getHeight() / 2;
	ByteBuffer buffer = ByteBuffer.allocate(bufferSize);
	buffer.order(ByteOrder.LITTLE_ENDIAN);
	buildHeaderDxt1(buffer, image.getWidth(), image.getHeight());

	int numTilesWide = image.getWidth() / 4;
	int numTilesHigh = image.getHeight() / 4;
	for (int i = 0; i < numTilesHigh; i++) {
		for (int j = 0; j < numTilesWide; j++) {
			java.awt.image.BufferedImage originalTile = image.getSubimage(j * 4, i * 4, 4, 4);
			originalTile.getRGB(0, 0, 4, 4, pixels, 0, 4);
			Color[] colors = getColors888(pixels);

			for (int k = 0; k < pixels.length; k++) {
				pixels[k] = getPixel565(colors[k]);
				colors[k] = getColor565(pixels[k]);
			}

			int[] extremaIndices = determineExtremeColors(colors);
			if (pixels[extremaIndices[0]] < pixels[extremaIndices[1]]) {
				int t = extremaIndices[0];
				extremaIndices[0] = extremaIndices[1];
				extremaIndices[1] = t;
			}

			buffer.putShort((short) pixels[extremaIndices[0]]);
			buffer.putShort((short) pixels[extremaIndices[1]]);

			long bitmask = computeBitMask(colors, extremaIndices);
			buffer.putInt((int) bitmask);
		}
	}

	return buffer;
}
 
Example 16
Source File: ShapeFileManage.java    From MeteoInfo with GNU Lesser General Public License v3.0 4 votes vote down vote up
private static VectorLayer readPolygonZShapes(DataInputStream br, int shapeNum) throws IOException {
    VectorLayer aLayer = new VectorLayer(ShapeTypes.PolygonZ);
    int RecordNum, ContentLength, aShapeType;
    double x, y;
    byte[] bytes;
    ByteBuffer buffer;

    for (int i = 0; i < shapeNum; i++) {            
        //br.skipBytes(12);
        bytes = new byte[8];
        br.read(bytes);
        buffer = ByteBuffer.wrap(bytes);
        //br.skipBytes(12); 
        buffer.order(ByteOrder.BIG_ENDIAN);
        RecordNum = buffer.getInt();
        ContentLength = buffer.getInt();
        
        bytes = new byte[ContentLength * 2];
        br.read(bytes);
        buffer = ByteBuffer.wrap(bytes);
        buffer.order(ByteOrder.LITTLE_ENDIAN);
        aShapeType = buffer.getInt();

        PolygonZShape aSPG = new PolygonZShape();
        Extent extent = new Extent();
        extent.minX = buffer.getDouble();
        extent.minY = buffer.getDouble();
        extent.maxX = buffer.getDouble();
        extent.maxY = buffer.getDouble();
        aSPG.setExtent(extent);
        aSPG.setPartNum(buffer.getInt());
        int numPoints = buffer.getInt();
        aSPG.parts = new int[aSPG.getPartNum()];
        List<PointD> points = new ArrayList<>();

        //firstly read out parts begin pos in file 
        for (int j = 0; j < aSPG.getPartNum(); j++) {
            aSPG.parts[j] = buffer.getInt();
        }

        //read out coordinates 
        for (int j = 0; j < numPoints; j++) {
            x = buffer.getDouble();
            y = buffer.getDouble();
            PointD aPoint = new PointD();
            aPoint.X = x;
            aPoint.Y = y;
            points.add(aPoint);
        }
        
        //Read Z
        double zmin = buffer.getDouble();
        double zmax = buffer.getDouble();
        double[] zArray = new double[numPoints];
        for (int j = 0; j < numPoints; j++) {
            zArray[j] = buffer.getDouble();
        }
        
        //Read measure
        double mmin = buffer.getDouble();
        double mmax = buffer.getDouble();
        double[] mArray = new double[numPoints];
        for (int j = 0; j < numPoints; j++) {
            mArray[j] = buffer.getDouble();
        }
        
        //Get pointZ list
        List<PointZ> pointZs = new ArrayList<>();
        for (int j = 0; j < numPoints; j++) {
            pointZs.add(new PointZ(points.get(j).X, points.get(j).Y, zArray[j], mArray[j]));
        }
        
        aSPG.setPoints(pointZs);
        aLayer.addShape(aSPG);
    }

    //Create legend scheme            
    aLayer.setLegendScheme(LegendManage.createSingleSymbolLegendScheme(ShapeTypes.Polygon, new Color(255, 251, 195), 1.0F));

    return aLayer;
}
 
Example 17
Source File: StringValuePart.java    From aion-germany with GNU General Public License v3.0 4 votes vote down vote up
@Override
public void parse(ByteBuffer buf)
{
    if(this.getMode() == DataPacketMode.FORGING)
        throw new IllegalStateException("Can not parse on a Forging mode Data Packet Tree element");
    int pos = buf.position();
    int size = 0;
    switch(_type)
    {
        case s:
            StringBuffer sb = new StringBuffer();
            byte b;
            while ((b = buf.get()) != 0)
                sb.append((char)b);
            _string = sb.toString();
            size = sb.length()+1;
            break;
        case S:
            StringBuffer sb2 = new StringBuffer();
            char ch;
            char first = buf.getChar();
            if (first == '$')
            {
            	boolean stringFallback = false;
            	while ((ch = buf.getChar()) != 0) {
            		if (ch == '$') {
            			stringFallback = true;
            		}
            		sb2.append(ch);
            	}
            	if (stringFallback) {
            		 _string = "$" + sb2.toString();
                	size = _string.length() * 2 + 2;
                	break;
            	}
            	size = sb2.length() * 2;
            	
            	buf.position(pos + 2);
            	byte[] bytes = new byte[size];
            	for (int i = 0; i < size; i++)
            		bytes[i] = buf.get();
            	
        		ByteBuffer buffer = ByteBuffer.allocate(bytes.length);
        		buffer.order(ByteOrder.LITTLE_ENDIAN);
        		buffer.put(bytes);
        		int value = 0;
        		if (bytes.length == 1)
        			value = buffer.get(0);
        		else if (bytes.length == 2)
        			value = buffer.getShort(0);
        		else if (bytes.length == 4)
        			value = buffer.getInt(0);
        		
        		_string = Long.toString(value);                 	
            	size += 4;
            }
            else
            {
            	buf.position(pos);
             while ((ch = buf.getChar()) != 0)
                 sb2.append(ch);
             _string = sb2.toString();
             size = sb2.length()*2+2;
            }
            break;
        case Ss:
            StringBuffer sb3 = new StringBuffer();
char ch1;
while ((ch1 = buf.getChar()) != 0)
{
	sb3.append(ch1);
}
_string = sb3.toString();
size = getBSize();
break;
        case Sn:
            StringBuffer sb4 = new StringBuffer();
for (int i = 0; i < super.getBSize(); i = i + 2)
{
	sb4.append(buf.getChar());
}
_string = sb4.toString();
size = getBSize();          	
        	break;
    }
    // sets the raw bytes
    _bytes = new byte[size];
    buf.position(pos);
    buf.get(_bytes);
}
 
Example 18
Source File: DictMergeTest.java    From indexr with Apache License 2.0 4 votes vote down vote up
private void check(Column column) throws IOException {
    ArrayList<DataPack> dps = new ArrayList<>();
    ArrayList<DictStruct> structs = new ArrayList<>();
    for (int packId = 0; packId < column.packCount(); packId++) {
        DataPackNode dpn = column.dpn(packId);
        if (dpn.isDictEncoded()) {
            DataPack pack = column.pack(packId);
            dps.add(pack);
            structs.add(pack.dictStruct(column.dataType(), dpn));
        }
    }

    DictStruct[] dictStructs = structs.toArray(new DictStruct[0]);
    DataPack[] dataPacks = dps.toArray(new DataPack[0]);

    DictMerge dictMerge = new DictMerge();
    dictMerge.merge(column.dataType(), dictStructs);

    Path entryFilePath = column.dataType() == ColumnType.STRING
            ? dictMerge.combineStringOffsetAndEntryFile() : dictMerge.entryFilePath();
    FileChannel entryFile = FileChannel.open(
            entryFilePath,
            StandardOpenOption.READ,
            StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);
    FileChannel bitmapFile = FileChannel.open(
            dictMerge.bitmapFilePath(),
            StandardOpenOption.READ,
            StandardOpenOption.CREATE,
            StandardOpenOption.TRUNCATE_EXISTING);

    ByteBuffer entryFileBuffer = entryFile.map(FileChannel.MapMode.READ_ONLY, 0, entryFile.size());
    ByteBuffer bitmapFileBuffer = bitmapFile.map(FileChannel.MapMode.READ_ONLY, 0, bitmapFile.size());

    entryFileBuffer.order(ByteOrder.nativeOrder());
    bitmapFileBuffer.order(ByteOrder.nativeOrder());

    ByteBufferReader entryFileReader = ByteBufferReader.of(entryFileBuffer, 0, null);

    switch (column.dataType()) {
        case ColumnType.INT:
            checkInts(dataPacks, dictMerge.entryCount(), entryFileReader, bitmapFileBuffer);
            break;
        case ColumnType.LONG:
            checkLongs(dataPacks, dictMerge.entryCount(), entryFileReader, bitmapFileBuffer);
            break;
        case ColumnType.FLOAT:
            checkFloats(dataPacks, dictMerge.entryCount(), entryFileReader, bitmapFileBuffer);
            break;
        case ColumnType.DOUBLE:
            checkDoubles(dataPacks, dictMerge.entryCount(), entryFileReader, bitmapFileBuffer);
            break;
        case ColumnType.STRING:
            checkStrings(dataPacks, dictMerge.entryCount(), entryFileReader, bitmapFileBuffer);
            break;
        default:
            throw new RuntimeException("Illegal data type");
    }

    dictMerge.free();
    dictMerge.clean();
    IOUtil.closeQuietly(entryFile);
    IOUtil.closeQuietly(bitmapFile);
    for (DataPack dataPack : dataPacks) {
        dataPack.free();
    }
}
 
Example 19
Source File: ColorFade.java    From android_9.0.0_r45 with Apache License 2.0 4 votes vote down vote up
private static FloatBuffer createNativeFloatBuffer(int size) {
    ByteBuffer bb = ByteBuffer.allocateDirect(size * 4);
    bb.order(ByteOrder.nativeOrder());
    return bb.asFloatBuffer();
}
 
Example 20
Source File: ModelLoadAndSaveSTL.java    From Robot-Overlord-App with GNU General Public License v2.0 4 votes vote down vote up
protected void loadBinary(BufferedInputStream inputStream,Model model) throws IOException {
	int j;

    byte[] headerInfo=new byte[80];             // Header data
    inputStream.read(headerInfo);

    byte[] arrayNumber= new byte[4];     // Holds the number of faces
    inputStream.read(arrayNumber);
    ByteBuffer dataBuffer = ByteBuffer.wrap(arrayNumber);
    dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
    int numTriangles = dataBuffer.getInt();
    int byteCount = 50;
    byte[] tempInfo = new byte[byteCount*numTriangles];     // Each face has 50 bytes of data
       inputStream.read(tempInfo);                         // We get the rest of the file
       dataBuffer = ByteBuffer.wrap(tempInfo);    // Now we have all the data in this ByteBuffer
       dataBuffer.order(ByteOrder.LITTLE_ENDIAN);
       		
	float x,y,z;
	for(j=0;j<numTriangles;++j) {
		x=dataBuffer.getFloat();
		y=dataBuffer.getFloat();
		z=dataBuffer.getFloat();

		model.addNormal(x, y, z);
		model.addNormal(x, y, z);
		model.addNormal(x, y, z);

		x=dataBuffer.getFloat();
		y=dataBuffer.getFloat();
		z=dataBuffer.getFloat();
		model.addVertex(x, y, z);

		x=dataBuffer.getFloat();
		y=dataBuffer.getFloat();
		z=dataBuffer.getFloat();
		model.addVertex(x, y, z);

		x=dataBuffer.getFloat();
		y=dataBuffer.getFloat();
		z=dataBuffer.getFloat();
		model.addVertex(x, y, z);
		
		// attribute bytes
		dataBuffer.get();
		dataBuffer.get();
	}
	model.hasNormals=true;
}