Example usage for java.nio ByteBuffer capacity

List of usage examples for java.nio ByteBuffer capacity

Introduction

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

Prototype

public final int capacity() 

Source Link

Document

Returns the capacity of this buffer.

Usage

From source file:xbird.storage.io.RemoteVarSegments.java

private ByteBuffer truncateBuffer(final ByteBuffer buf, final int size) {
    if (size > buf.capacity()) {
        _rbufPool.returnObject(buf);/*from   w w  w . ja va  2s  . c o m*/
        return ByteBuffer.allocate(size); // TODO REVIEWME
    } else {
        buf.clear();
        buf.limit(size);
        return buf;
    }
}

From source file:com.hadoop.compression.fourmc.Lz4Compressor.java

/**
 * Reallocates a direct byte buffer by freeing the old one and allocating
 * a new one, unless the size is the same, in which case it is simply
 * cleared and returned./*  www . j a  v a  2 s .com*/
 * <p/>
 * NOTE: this uses unsafe APIs to manually free memory - if anyone else
 * has a reference to the 'buf' parameter they will likely read random
 * data or cause a segfault by accessing it.
 */
private ByteBuffer realloc(ByteBuffer buf, int newSize) {
    if (buf != null) {
        if (buf.capacity() == newSize) {
            // Can use existing buffer
            buf.clear();
            return buf;
        }

        DirectBufferPool.getInstance().release(buf);
    }
    return DirectBufferPool.getInstance().allocate(newSize);
}

From source file:io.horizondb.io.buffers.DirectBuffer.java

/**
 * Creates a new <code>DirectBuffer</code> that wrap the specified <code>ByteBuffer</code>.
 * /*from  w  ww .  j a v a2s  .  c om*/
 * @param buffer the <code>ByteBuffer</code>.
 */
DirectBuffer(ByteBuffer buffer) {

    notNull(buffer, "the buffer parameter must not be null");
    isTrue(buffer.isDirect(), "the buffer must be direct");

    this.buffer = buffer;

    subRegion(0, buffer.capacity());
    writerIndex(buffer.capacity());
}

From source file:adminpassword.Decryption.java

@SuppressWarnings("static-access")
public String decrypt(String encryptedText, String idKey) throws Exception {
    String password = idKey;/* w w  w  .  ja  v a 2  s  . c o m*/

    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

    //strip off the salt and iv
    ByteBuffer buffer = ByteBuffer.wrap(new Base64().decode(encryptedText));
    byte[] saltBytes = new byte[20];
    buffer.get(saltBytes, 0, saltBytes.length);
    byte[] ivBytes1 = new byte[cipher.getBlockSize()];
    buffer.get(ivBytes1, 0, ivBytes1.length);
    byte[] encryptedTextBytes = new byte[buffer.capacity() - saltBytes.length - ivBytes1.length];
    buffer.get(encryptedTextBytes);

    // Deriving the key
    SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
    PBEKeySpec spec = new PBEKeySpec(password.toCharArray(), saltBytes, 65556, 256);

    SecretKey secretKey = factory.generateSecret(spec);
    SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
    cipher.init(Cipher.DECRYPT_MODE, secret, new IvParameterSpec(ivBytes1));

    byte[] decryptedTextBytes = null;
    try {
        decryptedTextBytes = cipher.doFinal(encryptedTextBytes);

    } catch (IllegalBlockSizeException e) {
        e.printStackTrace();
    } catch (BadPaddingException e) {
        e.printStackTrace();
    }

    return new String(decryptedTextBytes);
}

From source file:com.github.jinahya.verbose.codec.BinaryCodecTest.java

protected final void encodeDecode(final ReadableByteChannel expectedChannel) throws IOException {

    if (expectedChannel == null) {
        throw new NullPointerException("null expectedChannel");
    }// w w  w.  jav a 2  s.  c om

    final Path encodedPath = Files.createTempFile("test", null);
    getRuntime().addShutdownHook(new Thread(() -> {
        try {
            Files.delete(encodedPath);
        } catch (final IOException ioe) {
            ioe.printStackTrace(System.err);
        }
    }));
    final WritableByteChannel encodedChannel = FileChannel.open(encodedPath, StandardOpenOption.WRITE);

    final ByteBuffer decodedBuffer = ByteBuffer.allocate(128);
    final ByteBuffer encodedBuffer = ByteBuffer.allocate(decodedBuffer.capacity() << 1);

    while (expectedChannel.read(decodedBuffer) != -1) {
        decodedBuffer.flip(); // limit -> position; position -> zero
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact(); // position -> n  + 1; limit -> capacity
        decodedBuffer.compact();
    }

    decodedBuffer.flip();
    while (decodedBuffer.hasRemaining()) {
        encoder.encode(decodedBuffer, encodedBuffer);
        encodedBuffer.flip();
        encodedChannel.write(encodedBuffer);
        encodedBuffer.compact();
    }

    encodedBuffer.flip();
    while (encodedBuffer.hasRemaining()) {
        encodedChannel.write(encodedBuffer);
    }
}

From source file:org.wso2.identity.iml.dsl.mediators.SAMLRequestProcessor.java

@Override
public boolean receive(CarbonMessage carbonMessage, CarbonCallback carbonCallback) throws Exception {

    if (log.isDebugEnabled()) {
        log.debug("Message received at " + getName());
    }/* w  ww .j  av a2 s.com*/

    CarbonMessage newReq;

    byte[] bytes;

    String contentLength = carbonMessage.getHeader(Constants.HTTP_CONTENT_LENGTH);
    if (contentLength != null) {

        newReq = new DefaultCarbonMessage();
        bytes = new byte[Integer.parseInt(contentLength)];

        newReq.setHeaders(carbonMessage.getHeaders());
        carbonMessage.getProperties().forEach(newReq::setProperty);
        List<ByteBuffer> fullMessageBody = carbonMessage.getFullMessageBody();

        int offset = 0;

        for (ByteBuffer byteBuffer : fullMessageBody) {
            newReq.addMessageBody(byteBuffer);
            ByteBuffer duplicate = byteBuffer.duplicate();
            duplicate.get(bytes, offset, byteBuffer.capacity());
            offset = offset + duplicate.capacity();
        }
        newReq.setEndOfMsgAdded(true);

        String encodedRequest = new String(bytes);
        String urlDecodedRequest = URLDecoder.decode(encodedRequest.split("=", 2)[1],
                StandardCharsets.UTF_8.name());
        String decodedRequest = new String(Base64.getDecoder().decode(urlDecodedRequest));

        if (log.isDebugEnabled()) {
            log.debug("Decoded SAML request: " + decodedRequest);
        }

        AuthnRequest samlAuthnRequest = SAMLRequestParser(decodedRequest);

        RequestContext samlRequestContext = new RequestContext();
        samlRequestContext.setHeaders(carbonMessage.getHeaders());
        samlRequestContext.addContent("samlRequest", samlAuthnRequest);

        AuthenticationContext authenticationContext = new AuthenticationContext();
        authenticationContext.getRequestContextMap().put("saml", samlRequestContext);

        newReq.setProperty("authenticationContext", authenticationContext);

    } else {
        newReq = carbonMessage;
    }
    return next(newReq, carbonCallback);
}

From source file:MainActivity.java

protected void takePicture(View view) {
    if (null == mCameraDevice) {
        return;/*from   w  w  w .j a  v a2 s .  com*/
    }
    CameraManager manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
    try {
        CameraCharacteristics characteristics = manager.getCameraCharacteristics(mCameraDevice.getId());
        StreamConfigurationMap configurationMap = characteristics
                .get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
        if (configurationMap == null)
            return;
        Size largest = Collections.max(Arrays.asList(configurationMap.getOutputSizes(ImageFormat.JPEG)),
                new CompareSizesByArea());
        ImageReader reader = ImageReader.newInstance(largest.getWidth(), largest.getHeight(), ImageFormat.JPEG,
                1);
        List<Surface> outputSurfaces = new ArrayList<Surface>(2);
        outputSurfaces.add(reader.getSurface());
        outputSurfaces.add(new Surface(mTextureView.getSurfaceTexture()));
        final CaptureRequest.Builder captureBuilder = mCameraDevice
                .createCaptureRequest(CameraDevice.TEMPLATE_STILL_CAPTURE);
        captureBuilder.addTarget(reader.getSurface());
        captureBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
        ImageReader.OnImageAvailableListener readerListener = new ImageReader.OnImageAvailableListener() {
            @Override
            public void onImageAvailable(ImageReader reader) {
                Image image = null;
                try {
                    image = reader.acquireLatestImage();
                    ByteBuffer buffer = image.getPlanes()[0].getBuffer();
                    byte[] bytes = new byte[buffer.capacity()];
                    buffer.get(bytes);
                    OutputStream output = new FileOutputStream(getPictureFile());
                    output.write(bytes);
                    output.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (image != null) {
                        image.close();
                    }
                }
            }
        };
        HandlerThread thread = new HandlerThread("CameraPicture");
        thread.start();
        final Handler backgroudHandler = new Handler(thread.getLooper());
        reader.setOnImageAvailableListener(readerListener, backgroudHandler);
        final CameraCaptureSession.CaptureCallback captureCallback = new CameraCaptureSession.CaptureCallback() {
            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request,
                    TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);
                Toast.makeText(MainActivity.this, "Picture Saved", Toast.LENGTH_SHORT).show();
                startPreview(session);
            }
        };
        mCameraDevice.createCaptureSession(outputSurfaces, new CameraCaptureSession.StateCallback() {
            @Override
            public void onConfigured(CameraCaptureSession session) {
                try {
                    session.capture(captureBuilder.build(), captureCallback, backgroudHandler);
                } catch (CameraAccessException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onConfigureFailed(CameraCaptureSession session) {
            }
        }, backgroudHandler);
    } catch (CameraAccessException e) {
        e.printStackTrace();
    }
}

From source file:io.druid.segment.data.CompressedObjectStrategy.java

@Override
public ResourceHolder<T> fromByteBuffer(ByteBuffer buffer, int numBytes) {
    final ResourceHolder<ByteBuffer> bufHolder = CompressedPools.getByteBuf(order);
    final ByteBuffer buf = bufHolder.get();
    buf.position(0);//from  w  ww  . j  av a 2 s.co m
    buf.limit(buf.capacity());

    decompress(buffer, numBytes, buf);
    return new ResourceHolder<T>() {
        @Override
        public T get() {
            return converter.convert(buf);
        }

        @Override
        public void close() {
            bufHolder.close();
        }
    };
}

From source file:com.mellanox.jxio.Msg.java

private String toStringBB(ByteBuffer bb) {
    StringBuffer sb = new StringBuffer();
    sb.append("[pos=");
    sb.append(bb.position());/*from www.  j  ava 2 s  .  c o m*/
    sb.append(" lim=");
    sb.append(bb.limit());
    sb.append(" cap=");
    sb.append(bb.capacity());
    sb.append("]");
    return sb.toString();
}

From source file:com.gpl_compression.lzo.LzoCompressor.java

/**
 * Reallocates a direct byte buffer by freeing the old one and allocating
 * a new one, unless the size is the same, in which case it is simply
 * cleared and returned./* w  ww. j a va2s .  c  om*/
 *
 * NOTE: this uses unsafe APIs to manually free memory - if anyone else
 * has a reference to the 'buf' parameter they will likely read random
 * data or cause a segfault by accessing it.
 */
private ByteBuffer realloc(ByteBuffer buf, int newSize) {
    if (buf != null) {
        if (buf.capacity() == newSize) {
            // Can use existing buffer
            buf.clear();
            return buf;
        }
        try {
            // Manually free the old buffer using undocumented unsafe APIs.
            // If this fails, we'll drop the reference and hope GC finds it
            // eventually.
            Object cleaner = buf.getClass().getMethod("cleaner").invoke(buf);
            cleaner.getClass().getMethod("clean").invoke(cleaner);
        } catch (Exception e) {
            // Perhaps a non-sun-derived JVM - contributions welcome
            LOG.warn("Couldn't realloc bytebuffer", e);
        }
    }
    return ByteBuffer.allocateDirect(newSize);
}