Example usage for java.nio ByteBuffer arrayOffset

List of usage examples for java.nio ByteBuffer arrayOffset

Introduction

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

Prototype

public final int arrayOffset() 

Source Link

Document

Returns the offset of the byte array which this buffer is based on, if there is one.

Usage

From source file:org.ms123.common.git.FileHolder.java

public static byte[] encode(final String str) {
    final ByteBuffer bb = Constants.CHARSET.encode(str);
    final int len = bb.limit();
    if (bb.hasArray() && bb.arrayOffset() == 0) {
        final byte[] arr = bb.array();
        if (arr.length == len)
            return arr;
    }//w w  w  . ja  va2  s  .com
    final byte[] arr = new byte[len];
    bb.get(arr);
    return arr;
}

From source file:com.liveramp.commons.util.BytesUtils.java

public static int compareBytesUnsigned(ByteBuffer a, ByteBuffer b) {
    if (a.remaining() != b.remaining()) {
        throw new RuntimeException(
                "Cannot compare ByteBuffers that have a different number of remaining elements.");
    }//  w  ww  .ja  va2 s .  c  o m
    return compareBytesUnsigned(a.array(), a.arrayOffset() + a.position(), b.array(),
            b.arrayOffset() + b.position(), a.remaining());
}

From source file:com.icloud.framework.core.util.FBUtilities.java

public static String bytesToHex(ByteBuffer bytes) {
    StringBuilder sb = new StringBuilder();
    for (int i = bytes.position() + bytes.arrayOffset(); i < bytes.limit() + bytes.arrayOffset(); i++) {
        int bint = bytes.array()[i] & 0xff;
        if (bint <= 0xF)
            // toHexString does not 0 pad its results.
            sb.append("0");
        sb.append(Integer.toHexString(bint));
    }//  www. jav a 2s .  com
    return sb.toString();
}

From source file:com.icloud.framework.core.util.FBUtilities.java

public static void writeByteArray(ByteBuffer bytes, DataOutput out) throws IOException {
    out.writeInt(bytes.remaining());/*from  w w  w  . ja  va  2  s  .c o  m*/
    out.write(bytes.array(), bytes.position() + bytes.arrayOffset(), bytes.remaining());
}

From source file:Main.java

public static List<ByteBuffer> mergeAdjacentBuffers(List<ByteBuffer> paramList) {
    ArrayList localArrayList = new ArrayList(paramList.size());
    Iterator localIterator = paramList.iterator();
    while (localIterator.hasNext()) {
        ByteBuffer localByteBuffer1 = (ByteBuffer) localIterator.next();
        int i = -1 + localArrayList.size();
        if ((i >= 0) && (localByteBuffer1.hasArray()) && (((ByteBuffer) localArrayList.get(i)).hasArray())
                && (localByteBuffer1.array() == ((ByteBuffer) localArrayList.get(i)).array())
                && (((ByteBuffer) localArrayList.get(i)).arrayOffset()
                        + ((ByteBuffer) localArrayList.get(i)).limit() == localByteBuffer1.arrayOffset())) {
            ByteBuffer localByteBuffer3 = (ByteBuffer) localArrayList.remove(i);
            localArrayList.add(ByteBuffer.wrap(localByteBuffer1.array(), localByteBuffer3.arrayOffset(),
                    localByteBuffer3.limit() + localByteBuffer1.limit()).slice());
        } else if ((i >= 0) && ((localByteBuffer1 instanceof MappedByteBuffer))
                && ((localArrayList.get(i) instanceof MappedByteBuffer))
                && (((ByteBuffer) localArrayList.get(i))
                        .limit() == ((ByteBuffer) localArrayList.get(i)).capacity()
                                - localByteBuffer1.capacity())) {
            ByteBuffer localByteBuffer2 = (ByteBuffer) localArrayList.get(i);
            localByteBuffer2.limit(localByteBuffer1.limit() + localByteBuffer2.limit());
        } else {//  ww  w. j av  a 2  s.  c om
            localByteBuffer1.reset();
            localArrayList.add(localByteBuffer1);
        }
    }
    return localArrayList;
}

From source file:io.mycat.util.ByteBufferUtil.java

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

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

    return bytes;
}

From source file:org.apache.hadoop.hdfs.protocol.datatransfer.PacketReceiver.java

private static void doReadFully(ReadableByteChannel ch, InputStream in, ByteBuffer buf) throws IOException {
    if (ch != null) {
        readChannelFully(ch, buf);/*  w  w w. j a va 2 s .c o  m*/
    } else {
        Preconditions.checkState(!buf.isDirect(), "Must not use direct buffers with InputStream API");
        IOUtils.readFully(in, buf.array(), buf.arrayOffset() + buf.position(), buf.remaining());
        buf.position(buf.position() + buf.remaining());
    }
}

From source file:org.apache.solr.handler.TestBlobHandler.java

public static void postData(CloudSolrClient cloudClient, String baseUrl, String blobName, ByteBuffer bytarr)
        throws IOException {
    HttpPost httpPost = null;//from   ww w  .j  a va2 s . c  om
    HttpEntity entity;
    String response = null;
    try {
        httpPost = new HttpPost(baseUrl + "/.system/blob/" + blobName);
        httpPost.setHeader("Content-Type", "application/octet-stream");
        httpPost.setEntity(new ByteArrayEntity(bytarr.array(), bytarr.arrayOffset(), bytarr.limit()));
        entity = cloudClient.getLbClient().getHttpClient().execute(httpPost).getEntity();
        try {
            response = EntityUtils.toString(entity, StandardCharsets.UTF_8);
            Map m = (Map) ObjectBuilder.getVal(new JSONParser(new StringReader(response)));
            assertFalse("Error in posting blob " + getAsString(m), m.containsKey("error"));
        } catch (JSONParser.ParseException e) {
            log.error("$ERROR$", response, e);
            fail();
        }
    } finally {
        httpPost.releaseConnection();
    }
}

From source file:com.icloud.framework.core.nio.ByteBufferUtil.java

public static ByteBuffer clone(ByteBuffer o) {
    assert o != null;

    if (o.remaining() == 0)
        return ByteBuffer.wrap(ArrayUtils.EMPTY_BYTE_ARRAY);

    ByteBuffer clone = ByteBuffer.allocate(o.remaining());

    if (o.isDirect()) {
        for (int i = o.position(); i < o.limit(); i++) {
            clone.put(o.get(i));/*from  w ww .j  a  v  a2  s .  com*/
        }
        clone.flip();
    } else {
        System.arraycopy(o.array(), o.arrayOffset() + o.position(), clone.array(), 0, o.remaining());
    }

    return clone;
}

From source file:jp.andeb.obbutil.ObbUtilMain.java

private static boolean doAdd(String[] args) {
    final CommandLine commandLine;
    try {/* w  ww  .  j a va  2s  . c  o m*/
        final CommandLineParser parser = new GnuParser();
        commandLine = parser.parse(OPTIONS_FOR_ADD, args);
    } catch (MissingArgumentException e) {
        System.err.println("??????: " + e.getOption().getOpt());
        printUsage(PROGNAME);
        return false;
    } catch (MissingOptionException e) {
        System.err.println("??????: " + e.getMissingOptions());
        printUsage(PROGNAME);
        return false;
    } catch (UnrecognizedOptionException e) {
        System.err.println("????: " + e.getOption());
        printUsage(PROGNAME);
        return false;
    } catch (ParseException e) {
        System.err.println(e.getMessage());
        printUsage(PROGNAME);
        return false;
    }

    final String pkgName = commandLine.getOptionValue(PACKAGE_NAME.getOpt());
    final String versionStr = commandLine.getOptionValue(OBB_VERSION.getOpt());
    final Integer version = toInteger(versionStr);
    if (version == null) {
        System.err.println("??????: " + versionStr);
        printUsage(PROGNAME);
        return false;
    }
    final boolean isOverlay = commandLine.hasOption(OVERLAY_FLAG.getOpt());
    final String saltStr = commandLine.getOptionValue(SALT.getOpt());
    final byte[] salt;
    if (saltStr == null) {
        salt = null;
    } else {
        salt = toByteArray(saltStr, ObbInfoV1.SALT_LENGTH);
        if (salt == null) {
            System.err.println("????: " + saltStr);
            printUsage(PROGNAME);
            return false;
        }
    }

    final String[] nonRecognizedArgs = commandLine.getArgs();
    if (nonRecognizedArgs.length == 0) {
        System.err.println("????????");
        printUsage(PROGNAME);
        return false;
    }
    if (nonRecognizedArgs.length != 1) {
        System.err.println("???????");
        printUsage(PROGNAME);
        return false;
    }

    final File targetFile = new File(nonRecognizedArgs[0]);
    final RandomAccessFile targetRaFile;
    try {
        targetRaFile = new RandomAccessFile(targetFile, "rw");
    } catch (FileNotFoundException e) {
        System.err.println("????: " + targetFile.getPath());
        return false;
    }
    try {
        try {
            final ObbInfoV1 info = ObbInfoV1.fromFile(targetRaFile);
            System.err.println(
                    "?? OBB ???????: " + info.toString());
            return false;
        } catch (IOException e) {
            System.err
                    .println("????????: " + targetFile.getPath());
            return false;
        } catch (NotObbException e) {
            // 
        }

        int flag = 0;
        if (isOverlay) {
            flag |= ObbInfoV1.FLAG_OVERLAY;
        }
        if (salt != null) {
            flag |= ObbInfoV1.FLAG_SALTED;
        }
        final ObbInfoV1 obbInfo = new ObbInfoV1(flag, salt, pkgName, version.intValue());
        final ByteBuffer obbInfoBytes = obbInfo.toBytes();
        // ???
        targetRaFile.setLength(targetRaFile.length() + obbInfoBytes.remaining());
        targetRaFile.seek(targetRaFile.length() - obbInfoBytes.remaining());
        targetRaFile.write(obbInfoBytes.array(), obbInfoBytes.arrayOffset(), obbInfoBytes.remaining());
    } catch (IOException e) {
        System.err.println("OBB ?????????: " + targetFile.getPath());
        return false;
    } finally {
        try {
            targetRaFile.close();
        } catch (IOException e) {
            System.err.println("OBB ?????????: " + targetFile.getPath());
            return false;
        }
    }
    System.err.println("OBB ??????????: " + targetFile.getPath());
    return true;
}