Example usage for java.nio ByteBuffer hasArray

List of usage examples for java.nio ByteBuffer hasArray

Introduction

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

Prototype

public final boolean hasArray() 

Source Link

Document

Indicates whether this buffer is based on a byte array and provides read/write access.

Usage

From source file:org.eclipse.jgit.lfs.server.fs.LfsServerTest.java

private void checkResponseStatus(HttpResponse response) {
    StatusLine statusLine = response.getStatusLine();
    int status = statusLine.getStatusCode();
    if (statusLine.getStatusCode() >= 400) {
        String error;//from w ww.  jav  a 2 s. c  om
        try {
            ByteBuffer buf = IO.readWholeStream(new BufferedInputStream(response.getEntity().getContent()),
                    1024);
            if (buf.hasArray()) {
                error = new String(buf.array(), buf.arrayOffset() + buf.position(), buf.remaining(), UTF_8);
            } else {
                final byte[] b = new byte[buf.remaining()];
                buf.duplicate().get(b);
                error = new String(b, UTF_8);
            }
        } catch (IOException e) {
            error = statusLine.getReasonPhrase();
        }
        throw new RuntimeException("Status: " + status + " " + error);
    }
    assertEquals(200, status);
}

From source file:io.klerch.alexa.state.handler.AWSIotStateHandler.java

private String getState(final AlexaScope scope) throws AlexaStateException {
    final String thingName = getThingName(scope);

    createThingIfNotExisting(scope);/*from w  w w  .java2 s .c  om*/

    final GetThingShadowRequest awsRequest = new GetThingShadowRequest().withThingName(thingName);
    try {
        final GetThingShadowResult response = awsDataClient.getThingShadow(awsRequest);
        final ByteBuffer buffer = response.getPayload();

        try {
            return (buffer != null && buffer.hasArray()) ? new String(buffer.array(), "UTF-8") : "{}";
        } catch (UnsupportedEncodingException e) {
            final String error = format("Could not handle received contents of thing-shadow '%1$s'", thingName);
            log.error(error, e);
            throw AlexaStateException.create(error).withCause(e).withHandler(this).build();
        }
    }
    // if a thing does not have a shadow this is a usual exception
    catch (com.amazonaws.services.iotdata.model.ResourceNotFoundException e) {
        log.info(e);
        // we are fine with a thing having no shadow what just means there's nothing to read out for the model
        // return an empty JSON to indicate nothing is in the thing shadow
        return "{}";
    }
}

From source file:com.ery.ertc.estorm.util.Bytes.java

/**
 * Converts the given byte buffer to a printable representation, from the
 * index 0 (inclusive) to the limit (exclusive), regardless of the current
 * position. The position and the other index parameters are not changed.
 * /*from w  ww .  jav a  2  s  . c o  m*/
 * @param buf
 *            a byte buffer
 * @return a string representation of the buffer's binary contents
 * @see #toBytes(ByteBuffer)
 * @see #getBytes(ByteBuffer)
 */
public static String toStringBinary(ByteBuffer buf) {
    if (buf == null)
        return "null";
    if (buf.hasArray()) {
        return toStringBinary(buf.array(), buf.arrayOffset(), buf.limit());
    }
    return toStringBinary(toBytes(buf));
}

From source file:io.warp10.continuum.gts.GTSDecoder.java

/**
 * Return an encoder with all data from the last value retrieved (post call to next())
 * onwards// ww w .  j a v  a2s .c  om
 * 
 * @param safeMetadata Is it safe to reuse the Metadata?
 */
public GTSEncoder getEncoder(boolean safeMetadata) throws IOException {

    if (!nextCalled) {
        throw new IOException(
                "Can only get an encoder for a decoder on which 'next' was called at least once.");
    }

    //
    // Copy the remaining data into a new ByteBuffer
    //

    ByteBuffer bb = this.buffer.duplicate();
    bb.position(this.position);

    int offset = 0;
    int len = bb.remaining();
    byte[] bytes = null;

    if (bb.hasArray()) {
        bytes = bb.array();
        offset = bb.arrayOffset() + bb.position();
    } else {
        bytes = new byte[bb.remaining()];
        bb.get(bytes);
    }

    //
    // Create an encoder with the same base timestamp and wrapping key, providing a sizing hint
    //

    GTSEncoder encoder = new GTSEncoder(this.baseTimestamp, this.wrappingKey, bb.remaining());

    if (safeMetadata) {
        encoder.safeSetMetadata(this.getMetadata());
    } else {
        encoder.setMetadata(this.getMetadata());
    }

    //
    // Set initial values
    //

    encoder.initialize(this.previousLastTimestamp, this.previousLastGeoXPPoint, this.previousLastElevation,
            this.previousLastLongValue, this.previousLastDoubleValue, this.previousLastBDValue,
            this.previousLastStringValue);

    //
    // Copy the encoded data
    //

    encoder.stream.write(bytes, offset, len);

    //
    // Put the encoder into 'safe delta' mode, because we don't know what the last
    // value/ts/elevation/location were, we can't use delta encoding for now
    //

    encoder.safeDelta();

    encoder.setCount(this.count);

    return encoder;
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static byte[] charsToBytes(char[] chars) {
    if (chars == null)
        return null;

    Charset charset = Charset.forName("UTF-8");
    ByteBuffer byteBuffer = charset.encode(CharBuffer.wrap(chars));
    byte[] result = Arrays.copyOf(byteBuffer.array(), byteBuffer.limit());

    if (byteBuffer.hasArray()) {
        byte[] contentsToBeErased = byteBuffer.array();
        CryptoUtil.obscureBytes(contentsToBeErased, "random");
    }/*w  w  w . j a v  a 2  s  . co m*/
    return result;
}

From source file:com.servoy.j2db.util.Utils.java

public static byte[] readFile(File f, long size) {
    if (f != null && f.exists()) {

        FileInputStream fis = null;
        try {//w  ww.  j  a v  a  2 s  .co  m
            int length = (int) f.length();
            fis = new FileInputStream(f);
            FileChannel fc = fis.getChannel();
            if (size > length || size < 0)
                size = length;
            ByteBuffer bb = ByteBuffer.allocate((int) size);
            fc.read(bb);
            bb.rewind();
            byte[] bytes = null;
            if (bb.hasArray()) {
                bytes = bb.array();
            } else {
                bytes = new byte[(int) size];
                bb.get(bytes, 0, (int) size);
            }
            return bytes;
        } catch (Exception e) {
            Debug.error("Error reading file: " + f, e); //$NON-NLS-1$
        } finally {
            try {
                if (fis != null)
                    fis.close();
            } catch (Exception ex) {
            }
        }

        //         ByteArrayOutputStream sb = new ByteArrayOutputStream();
        //         try
        //         {
        //            FileInputStream is = new FileInputStream(f);
        //            BufferedInputStream bis = new BufferedInputStream(is);
        //            streamCopy(bis, sb);
        //            closeInputStream(bis);
        //         }
        //         catch (Exception e)
        //         {
        //            Debug.error(e);
        //         }
        //         return sb.toByteArray();
    }
    return null;
}

From source file:com.linkedin.databus.core.DbusEventBuffer.java

/**
 * Injects an event in the regular stream of events
 * @return true iff successful/*from www.j a  v a2s  .  c  om*/
 * @throws InvalidEventException
 */
public boolean injectEvent(DbusEventInternalReadable event) throws InvalidEventException {
    final ByteBuffer eventBuf = event.getRawBytes();
    byte[] cpEventBytes = null;
    if (eventBuf.hasArray()) {
        cpEventBytes = eventBuf.array();
    } else {
        cpEventBytes = new byte[event.getRawBytes().limit()];
        eventBuf.get(cpEventBytes);
    }
    ByteArrayInputStream cpIs = new ByteArrayInputStream(cpEventBytes);
    ReadableByteChannel cpRbc = Channels.newChannel(cpIs);
    int ecnt = readEvents(cpRbc);

    return ecnt > 0;
}

From source file:org.apache.axiom.attachments.impl.BufferUtils.java

/**
 * Opimized writing to FileOutputStream using a channel
 * @param is/*from   w ww  . j a v a 2s.c  o m*/
 * @param fos
 * @return false if lock was not aquired
 * @throws IOException
 */
public static boolean inputStream2FileOutputStream(InputStream is, FileOutputStream fos) throws IOException {

    // See if a file channel and lock can be obtained on the FileOutputStream
    FileChannel channel = null;
    FileLock lock = null;
    ByteBuffer bb = null;
    try {
        channel = fos.getChannel();
        if (channel != null) {
            lock = channel.tryLock();
        }
        bb = getTempByteBuffer();
    } catch (Throwable t) {
    }
    if (lock == null || bb == null || !bb.hasArray()) {
        releaseTempByteBuffer(bb);
        return false; // lock could not be set or bb does not have direct array access
    }

    try {

        // Read directly into the ByteBuffer array
        int bytesRead = is.read(bb.array());
        // Continue reading until no bytes are read and no
        // bytes are now available.
        while (bytesRead > 0 || is.available() > 0) {
            if (bytesRead > 0) {
                int written = 0;

                if (bytesRead < BUFFER_LEN) {
                    // If the ByteBuffer is not full, allocate a new one
                    ByteBuffer temp = ByteBuffer.allocate(bytesRead);
                    temp.put(bb.array(), 0, bytesRead);
                    temp.position(0);
                    written = channel.write(temp);
                } else {
                    // Write to channel
                    bb.position(0);
                    written = channel.write(bb);
                    bb.clear();
                }

            }

            // REVIEW: Do we need to ensure that bytesWritten is 
            // the same as the number of bytes sent ?

            bytesRead = is.read(bb.array());
        }
    } finally {
        // Release the lock
        lock.release();
        releaseTempByteBuffer(bb);
    }
    return true;
}

From source file:org.apache.cassandra.utils.ByteBufferUtil.java

/**
 * You should almost never use this.  Instead, use the write* methods to avoid copies.
 *//*w w  w. j  a  v  a 2s.co m*/
public static byte[] getArray(ByteBuffer buffer) {
    int length = buffer.remaining();

    if (buffer.hasArray()) {
        int start = buffer.position();
        if (buffer.arrayOffset() == 0 && start == 0 && length == buffer.array().length)
            return buffer.array();
        else
            return Arrays.copyOfRange(buffer.array(), start + buffer.arrayOffset(),
                    start + length + buffer.arrayOffset());
    }
    // else, DirectByteBuffer.get() is the fastest route
    byte[] bytes = new byte[length];
    buffer.duplicate().get(bytes);

    return bytes;
}

From source file:org.apache.cassandra.utils.ByteBufferUtil.java

/**
 * Transfer bytes from one ByteBuffer to another.
 * This function acts as System.arrayCopy() but for ByteBuffers.
 *
 * @param src the source ByteBuffer/* w  w w .  j  a v  a2s .com*/
 * @param srcPos starting position in the source ByteBuffer
 * @param dst the destination ByteBuffer
 * @param dstPos starting position in the destination ByteBuffer
 * @param length the number of bytes to copy
 */
public static void arrayCopy(ByteBuffer src, int srcPos, ByteBuffer dst, int dstPos, int length) {
    if (src.hasArray() && dst.hasArray()) {
        System.arraycopy(src.array(), src.arrayOffset() + srcPos, dst.array(), dst.arrayOffset() + dstPos,
                length);
    } else {
        if (src.limit() - srcPos < length || dst.limit() - dstPos < length)
            throw new IndexOutOfBoundsException();

        for (int i = 0; i < length; i++) {
            dst.put(dstPos++, src.get(srcPos++));
        }
    }
}