Java Code Examples for java.nio.ByteBuffer.allocateDirect()

The following are Jave code examples for showing how to use allocateDirect() of the java.nio.ByteBuffer class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: kafka-0.11.0.0-src-with-comment   File: UtilsTest.java   View Source Code Vote up 6 votes
@Test
public void toArrayDirectByteBuffer() {
    byte[] input = {0, 1, 2, 3, 4};
    ByteBuffer buffer = ByteBuffer.allocateDirect(5);
    buffer.put(input);
    buffer.rewind();

    assertArrayEquals(input, Utils.toArray(buffer));
    assertEquals(0, buffer.position());

    assertArrayEquals(new byte[] {1, 2}, Utils.toArray(buffer, 1, 2));
    assertEquals(0, buffer.position());

    buffer.position(2);
    assertArrayEquals(new byte[] {2, 3, 4}, Utils.toArray(buffer));
    assertEquals(2, buffer.position());
}
 
Example 2
Project: TriMeshKit   File: BufferUtility.java   View Source Code Vote up 5 votes
public static Buffer getFloatBuffer(float[] array) {
	// Each float takes 4 bytes
       ByteBuffer byteBuffer = ByteBuffer.allocateDirect((Float.SIZE / Byte.SIZE) * array.length);
       byteBuffer.order(ByteOrder.nativeOrder());
       for (float d : array)
           byteBuffer.putFloat(d);
       
       byteBuffer.rewind();

       return byteBuffer;
}
 
Example 3
Project: ProjectAres   File: PacketTracer.java   View Source Code Vote up 5 votes
@Override
public int writeBytes(ScatteringByteChannel ch, int max) throws IOException {
    ByteBuffer tmp = ByteBuffer.allocateDirect(max);
    int length = ch.read(tmp);
    writeBytes(tmp);
    return length;
}
 
Example 4
Project: hadoop-oss   File: BufferAllocator.java   View Source Code Vote up 5 votes
@Override
public ByteBuffer allocate(int bufferLen) {
  if (bufferLen > overallBuffer.capacity() - overallBuffer.position()) {
    // If no available space for the requested length, then allocate new
    return isUsingDirect() ? ByteBuffer.allocateDirect(bufferLen) :
        ByteBuffer.allocate(bufferLen);
  }

  overallBuffer.limit(overallBuffer.position() + bufferLen);
  ByteBuffer result = overallBuffer.slice();
  overallBuffer.position(overallBuffer.position() + bufferLen);
  return result;
}
 
Example 5
Project: PlusGram   File: PhotoFilterView.java   View Source Code Vote up 5 votes
private Bitmap getRenderBufferBitmap() {
    ByteBuffer buffer = ByteBuffer.allocateDirect(renderBufferWidth * renderBufferHeight * 4);
    GLES20.glReadPixels(0, 0, renderBufferWidth, renderBufferHeight, GLES20.GL_RGBA, GLES20.GL_UNSIGNED_BYTE, buffer);
    Bitmap bitmap = Bitmap.createBitmap(renderBufferWidth, renderBufferHeight, Bitmap.Config.ARGB_8888);
    bitmap.copyPixelsFromBuffer(buffer);
    return bitmap;
}
 
Example 6
Project: creacoinj   File: NativeSecp256k1.java   View Source Code Vote up 5 votes
/**
 * libsecp256k1 PubKey Tweak-Add - Tweak pubkey by adding to it
 *
 * @param tweak some bytes to tweak with
 * @param pubkey 32-byte seckey
 */
public static byte[] pubKeyTweakAdd(byte[] pubkey, byte[] tweak) throws AssertFailException {
    Preconditions.checkArgument(pubkey.length == 33 || pubkey.length == 65);

    ByteBuffer byteBuff = nativeECDSABuffer.get();
    if (byteBuff == null || byteBuff.capacity() < pubkey.length + tweak.length) {
        byteBuff = ByteBuffer.allocateDirect(pubkey.length + tweak.length);
        byteBuff.order(ByteOrder.nativeOrder());
        nativeECDSABuffer.set(byteBuff);
    }
    byteBuff.rewind();
    byteBuff.put(pubkey);
    byteBuff.put(tweak);

    byte[][] retByteArray;
    r.lock();
    try {
        retByteArray = secp256k1_pubkey_tweak_add(byteBuff, Secp256k1Context.getContext(), pubkey.length);
    } finally {
        r.unlock();
    }

    byte[] pubArr = retByteArray[0];

    int pubLen = (byte) new BigInteger(new byte[] { retByteArray[1][0] }).intValue() & 0xFF;
    int retVal = new BigInteger(new byte[] { retByteArray[1][1] }).intValue();

    assertEquals(pubArr.length, pubLen, "Got bad pubkey length.");

    assertEquals(retVal, 1, "Failed return value check.");

    return pubArr;
}
 
Example 7
Project: dble   File: BufferPerformanceMain.java   View Source Code Vote up 5 votes
public void getAllocateDirect() {
    ByteBuffer buffer = ByteBuffer.allocateDirect(4096);
    byte[] b = new byte[1024];

    int count = 1000000;
    System.currentTimeMillis();

    long t1 = System.currentTimeMillis();
    for (int i = 0; i < count; i++) {
        buffer.position(0);
        buffer.get(b);
    }
    long t2 = System.currentTimeMillis();
    System.out.println("take time:" + (t2 - t1) + " ms.(Get:allocateDirect)");
}
 
Example 8
Project: apache-tomcat-7.0.73-with-comment   File: AprServletOutputStream.java   View Source Code Vote up 5 votes
public AprServletOutputStream(SocketWrapper<Long> wrapper,
        int asyncWriteBufferSize, AprEndpoint endpoint) {
    super(asyncWriteBufferSize);
    this.endpoint = endpoint;
    this.wrapper = wrapper;
    this.socket = wrapper.getSocket().longValue();
    if (endpoint.isSSLEnabled()) {
        sslOutputBuffer = ByteBuffer.allocateDirect(SSL_OUTPUT_BUFFER_SIZE);
        sslOutputBuffer.position(SSL_OUTPUT_BUFFER_SIZE);
    } else {
        sslOutputBuffer = null;
    }
}
 
Example 9
Project: openjdk-jdk10   File: SameBuffer.java   View Source Code Vote up 5 votes
private void doTestWithSeparatedBuffer(int offset,
        AlgorithmParameters params) throws Exception {
    // prepare AAD byte buffers to test
    byte[] AAD = Helper.generateBytes(AADLength);
    ByteBuffer AAD_Buf = ByteBuffer.allocate(AADLength);
    AAD_Buf.put(AAD, 0, AAD.length);
    AAD_Buf.flip();

    // prepare text byte buffer to encrypt/decrypt
    Cipher c = createCipher(Cipher.ENCRYPT_MODE, params);
    int outputLength = c.getOutputSize(textLength);
    int outputBufSize = outputLength + offset;
    byte[] inputText = Helper.generateBytes(outputBufSize);
    ByteBuffer plainTextBB = ByteBuffer.allocateDirect(inputText.length);
    plainTextBB.put(inputText);
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength);

    // do test
    runGCMWithSeparateBuffers(Cipher.ENCRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength, params);
    int tagLength = c.getParameters()
            .getParameterSpec(GCMParameterSpec.class).getTLen() / 8;
    plainTextBB.position(offset);
    plainTextBB.limit(offset + textLength + tagLength);
    runGCMWithSeparateBuffers(Cipher.DECRYPT_MODE, AAD_Buf, plainTextBB, offset,
            textLength + tagLength, params);
}
 
Example 10
Project: Muse-EEG-Toolkit   File: GraphGLLine.java   View Source Code Vote up 5 votes
/**
 * Convert the timeseries snapshot into a run of (x, y, z) bytes.
 */
private FloatBuffer snapshotToBuffer(TimeSeriesSnapshot snapshot) {
  float[] asFloats = snapshotToFloat(snapshot);

  // Create buffer to store result.
  ByteBuffer bb = ByteBuffer.allocateDirect(snapshot.length * VERTEX_STRIDE);
  bb.order(ByteOrder.nativeOrder());

  // Write to buffer usign floats:
  FloatBuffer vertexBuffer = bb.asFloatBuffer();
  vertexBuffer.put(asFloats);
  vertexBuffer.position(0);
  return vertexBuffer;
}
 
Example 11
Project: SmartMath   File: OGLChart.java   View Source Code Vote up 5 votes
public Bitmap takeScreenSnapshot(GL10 gl)	{
	int width = (int) mdChartWindowWidth;
	int height = (int) mdChartWindowHeight;
    int screenshotSize = width * height;
    int pixelsBuffer[] = new int[screenshotSize];
    try {
	    ByteBuffer bb = ByteBuffer.allocateDirect(screenshotSize * 4);
	    bb.order(ByteOrder.nativeOrder());
	    // this statement does not work in the landscape mode of galaxy express. Seems that it cannot support so large height (lines).
	    //gl.glReadPixels(0, 0, width, height, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
	    gl.glReadPixels(0, 0, width, height/2, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
	    bb.asIntBuffer().get(pixelsBuffer);
	    gl.glReadPixels(0, height/2, width, height/2, GL10.GL_RGBA, GL10.GL_UNSIGNED_BYTE, bb);
	    int pixelsBufferBottom[] = new int[screenshotSize];
	    bb.asIntBuffer().get(pixelsBufferBottom);
	    for (int idx = screenshotSize/2; idx < screenshotSize; idx ++)	{
	    	pixelsBuffer[idx] = pixelsBufferBottom[idx - screenshotSize/2];
	    }
	    bb = null;
    } catch (OutOfMemoryError  e)	{
    	// ByteBuffer.allocateDirect(screenshotSize * 4); could be out of memory
    	// in general, OutOfMemoryError should not be handled and developer should let JVM die.
    	// however, in this case, we know what statement causes the out of memory error
    	// and other threads are not affected. So it is ok to catch it.
    }

    for (int i = 0; i < screenshotSize; ++i) {
        // The alpha and green channels' positions are preserved while the red and blue are swapped
        pixelsBuffer[i] = ((pixelsBuffer[i] & 0xff00ff00)) | ((pixelsBuffer[i] & 0x000000ff) << 16) | ((pixelsBuffer[i] & 0x00ff0000) >> 16);
    }

    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixelsBuffer, screenshotSize-width, -width, 0, 0, width, height);
    return bitmap;
}
 
Example 12
Project: 19porn   File: OpenGlUtils.java   View Source Code Vote up 5 votes
public static ShortBuffer createShortBuffer(short[] coords) {
    ByteBuffer bb = ByteBuffer.allocateDirect(coords.length * SIZEOF_SHORT);
    bb.order(ByteOrder.nativeOrder());
    ShortBuffer ib = bb.asShortBuffer();
    ib.put(coords);
    ib.position(0);
    return ib;
}
 
Example 13
Project: hadoop-oss   File: ZlibCompressor.java   View Source Code Vote up 5 votes
/** 
 * Creates a new compressor using the specified compression level.
 * Compressed data will be generated in ZLIB format.
 * 
 * @param level Compression level #CompressionLevel
 * @param strategy Compression strategy #CompressionStrategy
 * @param header Compression header #CompressionHeader
 * @param directBufferSize Size of the direct buffer to be used.
 */
public ZlibCompressor(CompressionLevel level, CompressionStrategy strategy, 
                      CompressionHeader header, int directBufferSize) {
  this.level = level;
  this.strategy = strategy;
  this.windowBits = header;
  stream = init(this.level.compressionLevel(), 
                this.strategy.compressionStrategy(), 
                this.windowBits.windowBits());

  this.directBufferSize = directBufferSize;
  uncompressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
  compressedDirectBuf = ByteBuffer.allocateDirect(directBufferSize);
  compressedDirectBuf.position(directBufferSize);
}
 
Example 14
Project: imagej-tensorflow   File: TensorsTest.java   View Source Code Vote up 4 votes
/** Tests the img<Type>Direct(Tensor) functions */
@Test
public void testTensorToImgDirect() {
	final long[] shape = new long[] { 20, 10, 3 };
	final int[] mapping = new int[] { 0, 1, 2 };
	final int n = shape.length;
	final int size = 600;

	// Get some points to mark
	List<Point> points = createTestPoints(n);

	// Create Tensors of different type and convert them to images
	ByteBuffer dataByte = ByteBuffer.allocateDirect(size);
	execForPointsWithBufferIndex(shape, mapping, points, (i, v) -> dataByte.put(i, (byte) (int) v));
	Tensor tensorByte = Tensor.create(DataType.UINT8, shape, dataByte);
	Img<ByteType> imgByte = Tensors.imgByteDirect(tensorByte);

	DoubleBuffer dataDouble = DoubleBuffer.allocate(size);
	execForPointsWithBufferIndex(shape, mapping, points, (i, v) -> dataDouble.put(i, v));
	Tensor tensorDouble = Tensor.create(shape, dataDouble);
	Img<DoubleType> imgDouble = Tensors.imgDoubleDirect(tensorDouble);

	FloatBuffer dataFloat = FloatBuffer.allocate(size);
	execForPointsWithBufferIndex(shape, mapping, points, (i, v) -> dataFloat.put(i, v));
	Tensor tensorFloat = Tensor.create(shape, dataFloat);
	Img<FloatType> imgFloat = Tensors.imgFloatDirect(tensorFloat);

	IntBuffer dataInt = IntBuffer.allocate(size);
	execForPointsWithBufferIndex(shape, mapping, points, (i, v) -> dataInt.put(i, v));
	Tensor tensorInt = Tensor.create(shape, dataInt);
	Img<IntType> imgInt = Tensors.imgIntDirect(tensorInt);

	LongBuffer dataLong = LongBuffer.allocate(size);
	execForPointsWithBufferIndex(shape, mapping, points, (i, v) -> dataLong.put(i, v));
	Tensor tensorLong = Tensor.create(shape, dataLong);
	Img<LongType> imgLong = Tensors.imgLongDirect(tensorLong);

	// Check all created images
	checkImage(imgByte, n, shape, points);
	checkImage(imgDouble, n, shape, points);
	checkImage(imgFloat, n, shape, points);
	checkImage(imgInt, n, shape, points);
	checkImage(imgLong, n, shape, points);
}
 
Example 15
Project: openjdk-jdk10   File: StressLoopback.java   View Source Code Vote up 4 votes
Sink(AsynchronousByteChannel channel) {
    this.channel = channel;
    int size = 1024 + rand.nextInt(10000);
    this.readBuffer = (rand.nextBoolean()) ?
        ByteBuffer.allocateDirect(size) : ByteBuffer.allocate(size);
}
 
Example 16
Project: openjdk-jdk10   File: CRCTest.java   View Source Code Vote up 4 votes
private static void updateDirect(CRC32 crc3, byte[] b, int start, int length) {
    ByteBuffer buf = ByteBuffer.allocateDirect(length);
    buf.put(b, start, length);
    buf.flip();
    crc3.update(buf);
}
 
Example 17
Project: MegviiFacepp-Android-SDK   File: PointsMatrix.java   View Source Code Vote up 4 votes
public PointsMatrix(boolean isFaceCompare) {
	// FloatBuffer fb_0 = floatBufferUtil(squareCoords);
	// FloatBuffer fb_1 = floatBufferUtil(squareCoords_1);
	// vertexBuffers.add(fb_0);
	// vertexBuffers.add(fb_1);
	// initialize byte buffer for the draw list
	this.isFaceCompare = isFaceCompare;

	ByteBuffer dlb = ByteBuffer.allocateDirect(
			// (# of coordinate values * 2 bytes per short)
			drawOrder.length * 2);
	dlb.order(ByteOrder.nativeOrder());
	drawListBuffer = dlb.asShortBuffer();
	drawListBuffer.put(drawOrder);
	drawListBuffer.position(0);
	ByteBuffer line_dlb = ByteBuffer.allocateDirect(
			// (# of coordinate values * 2 bytes per short)
			drawLineOrder.length * 2);
	line_dlb.order(ByteOrder.nativeOrder());
	drawLineListBuffer = line_dlb.asShortBuffer();
	drawLineListBuffer.put(drawLineOrder);
	drawLineListBuffer.position(0);
	for (int i = 0; i < cubeOrders.length; ++i) {
		final short cubeOrder[] = cubeOrders[i];
		ByteBuffer cubedlb = ByteBuffer.allocateDirect(
				// (# of coordinate values * 2 bytes per short)
				cubeOrder.length * 2);
		cubedlb.order(ByteOrder.nativeOrder());
		cubeListBuffer[i] = cubedlb.asShortBuffer();
		cubeListBuffer[i].put(cubeOrder);
		cubeListBuffer[i].position(0);
	}

	ByteBuffer faceRectLDB = ByteBuffer.allocateDirect(drawFaceRectOrder.length * 2);
	faceRectLDB.order(ByteOrder.nativeOrder());
	faceRectListBuffer = faceRectLDB.asShortBuffer();
	faceRectListBuffer.put(drawFaceRectOrder);
	faceRectListBuffer.position(0);

	// prepare shaders and OpenGL program
	int vertexShader = loadShader(GLES20.GL_VERTEX_SHADER, vertexShaderCode);
	int fragmentShader = loadShader(GLES20.GL_FRAGMENT_SHADER, fragmentShaderCode);

	mProgram = GLES20.glCreateProgram(); // create empty OpenGL Program
	GLES20.glAttachShader(mProgram, vertexShader); // add the vertex shader
	// to program
	GLES20.glAttachShader(mProgram, fragmentShader); // add the fragment
	// shader to program
	GLES20.glLinkProgram(mProgram); // create OpenGL program executables
}
 
Example 18
Project: flume-release-1.7.0   File: ResettableFileInputStream.java   View Source Code Vote up 4 votes
/**
 *
 * @param file
 *        File to read
 *
 * @param tracker
 *        PositionTracker implementation to make offset position durable
 *
 * @param bufSize
 *        Size of the underlying buffer used for input. If lesser than {@link #MIN_BUF_SIZE},
 *        a buffer of length {@link #MIN_BUF_SIZE} will be created instead.
 *
 * @param charset
 *        Character set used for decoding text, as necessary
 *
 * @param decodeErrorPolicy
 *        A {@link DecodeErrorPolicy} instance to determine how
 *        the decoder should behave in case of malformed input and/or
 *        unmappable character.
 *
 * @throws FileNotFoundException If the file to read does not exist
 * @throws IOException If the position reported by the tracker cannot be sought
 */
public ResettableFileInputStream(File file, PositionTracker tracker,
    int bufSize, Charset charset, DecodeErrorPolicy decodeErrorPolicy)
    throws IOException {
  this.file = file;
  this.tracker = tracker;
  this.in = new FileInputStream(file);
  this.chan = in.getChannel();
  this.buf = ByteBuffer.allocateDirect(Math.max(bufSize, MIN_BUF_SIZE));
  buf.flip();
  this.byteBuf = new byte[1]; // single byte
  this.charBuf = CharBuffer.allocate(2); // two chars for surrogate pairs
  charBuf.flip();
  this.fileSize = file.length();
  this.decoder = charset.newDecoder();
  this.position = 0;
  this.syncPosition = 0;
  if (charset.name().startsWith("UTF-8")) {
    // some JDKs wrongly report 3 bytes max
    this.maxCharWidth = 4;
  } else if (charset.name().startsWith("UTF-16")) {
    // UTF_16BE and UTF_16LE wrongly report 2 bytes max
    this.maxCharWidth = 4;
  } else if (charset.name().startsWith("UTF-32")) {
    // UTF_32BE and UTF_32LE wrongly report 4 bytes max
    this.maxCharWidth = 8;
  } else {
    this.maxCharWidth = (int) Math.ceil(charset.newEncoder().maxBytesPerChar());
  }

  CodingErrorAction errorAction;
  switch (decodeErrorPolicy) {
    case FAIL:
      errorAction = CodingErrorAction.REPORT;
      break;
    case REPLACE:
      errorAction = CodingErrorAction.REPLACE;
      break;
    case IGNORE:
      errorAction = CodingErrorAction.IGNORE;
      break;
    default:
      throw new IllegalArgumentException(
          "Unexpected value for decode error policy: " + decodeErrorPolicy);
  }
  decoder.onMalformedInput(errorAction);
  decoder.onUnmappableCharacter(errorAction);

  seek(tracker.getPosition());
}
 
Example 19
Project: jdk8u-jdk   File: Receive.java   View Source Code Vote up 4 votes
@Override
public void run() {
    try {
        SctpChannel sc = ssc.accept();

        /* send a small message */
        MessageInfo info = MessageInfo.createOutgoing(null, 0)
                .payloadProtocolID(PPID);
        ByteBuffer buf = ByteBuffer.allocateDirect(Util.SMALL_BUFFER);
        buf.put(Util.SMALL_MESSAGE.getBytes("ISO-8859-1"));
        buf.flip();

        debug("sending small message: " + buf);
        sc.send(buf, info);

        /* send a large message */
        buf = ByteBuffer.allocateDirect(Util.LARGE_BUFFER);
        buf.put(Util.LARGE_MESSAGE.getBytes("ISO-8859-1"));
        buf.flip();

        debug("sending large message: " + buf);
        sc.send(buf, info);
        sc.shutdown();
        debug("shutdown");
        ReceiveNotificationHandler handler =
            new ReceiveNotificationHandler(sc);
        sc.receive(buf, null, handler);
        sc.close();

        /* accept another socket for the TEST 6 */
        sc = ssc.accept();
        ssc.close();

        clientFinishedLatch.await(10L, TimeUnit.SECONDS);
        serverFinishedLatch.countDown();
        sc.close();
    } catch (IOException ioe) {
        unexpected(ioe);
    } catch (InterruptedException ie) {
        unexpected(ie);
    }
}
 
Example 20
Project: GLproject   File: Circle.java   View Source Code Vote up 4 votes
private void initVertexData() {
    int n = 10;
    vCount = n + 2;
    float angleSpan = 360.0f / n;

    float[] vertices = new float[vCount * 3];
    int count = 0;
    //第一个坐标点
    vertices[count++] = 0;
    vertices[count++] = 0;
    vertices[count++] = 0;

    for (float angleTemp = 0; Math.ceil(angleTemp) <= 360 ; angleTemp += angleSpan) {
        double angrad = Math.toRadians(angleTemp);

        vertices[count++] = (float)(-Constant.UNIT_SIZE * Math.sin(angrad));
        vertices[count++] = (float)(Constant.UNIT_SIZE * Math.cos(angrad));
        vertices[count++] = 0;
    }
    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
    vbb.order(ByteOrder.nativeOrder());
    mVertexBuffer = vbb.asFloatBuffer();
    mVertexBuffer.put(vertices).position(0);

    float[] colors = new float[vCount * 4];
    count = 0;
    colors[count++] = 1;
    colors[count++] = 1;
    colors[count++] = 1;
    colors[count++] = 0;
    for (int i = 4; i < colors.length; i += 4) {
        colors[count++] = 0;
        colors[count++] = 1;
        colors[count++] = 0;
        colors[count++] = 0;
    }
    ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * 4);
    cbb.order(ByteOrder.nativeOrder());
    mColorBuffer = cbb.asFloatBuffer();
    mColorBuffer.put(colors).position(0);
}