Example usage for java.nio ByteBuffer array

List of usage examples for java.nio ByteBuffer array

Introduction

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

Prototype

public final byte[] array() 

Source Link

Document

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

Usage

From source file:com.twinsoft.convertigo.beans.steps.WriteXMLStep.java

protected void writeFile(String filePath, NodeList nodeList) throws EngineException {
    if (nodeList == null) {
        throw new EngineException("Unable to write to xml file: element is Null");
    }/*from  w  w w .j av  a 2 s.  co  m*/

    String fullPathName = getAbsoluteFilePath(filePath);
    synchronized (Engine.theApp.filePropertyManager.getMutex(fullPathName)) {
        try {
            String encoding = getEncoding();
            encoding = encoding.length() > 0 && Charset.isSupported(encoding) ? encoding : "UTF-8";
            if (!isReallyAppend(fullPathName)) {
                String tTag = defaultRootTagname.length() > 0 ? StringUtils.normalize(defaultRootTagname)
                        : "document";
                FileUtils.write(new File(fullPathName),
                        "<?xml version=\"1.0\" encoding=\"" + encoding + "\"?>\n<" + tTag + "/>", encoding);
            }

            StringBuffer content = new StringBuffer();

            /* do the content, only append child element */
            for (int i = 0; i < nodeList.getLength(); i++) {
                if (nodeList.item(i).getNodeType() == Node.ELEMENT_NODE) {
                    content.append(XMLUtils.prettyPrintElement((Element) nodeList.item(i), true, true));
                }
            }

            /* detect current xml encoding */
            RandomAccessFile randomAccessFile = null;
            try {
                randomAccessFile = new RandomAccessFile(fullPathName, "rw");
                FileChannel fc = randomAccessFile.getChannel();
                ByteBuffer buf = ByteBuffer.allocate(60);
                int nb = fc.read(buf);
                String sbuf = new String(buf.array(), 0, nb, "ASCII");
                String enc = sbuf.replaceFirst("^.*encoding=\"", "").replaceFirst("\"[\\d\\D]*$", "");

                if (!Charset.isSupported(enc)) {
                    enc = encoding;
                }

                buf.clear();

                /* retrieve last header tag*/
                long pos = fc.size() - buf.capacity();
                if (pos < 0) {
                    pos = 0;
                }

                nb = fc.read(buf, pos);

                boolean isUTF8 = Charset.forName(enc) == Charset.forName("UTF-8");

                if (isUTF8) {
                    for (int i = 0; i < buf.capacity(); i++) {
                        sbuf = new String(buf.array(), i, nb - i, enc);
                        if (!sbuf.startsWith("")) {
                            pos += i;
                            break;
                        }
                    }
                } else {
                    sbuf = new String(buf.array(), 0, nb, enc);
                }

                int lastTagIndex = sbuf.lastIndexOf("</");
                if (lastTagIndex == -1) {
                    int iend = sbuf.lastIndexOf("/>");
                    if (iend != -1) {
                        lastTagIndex = sbuf.lastIndexOf("<", iend);
                        String tagname = sbuf.substring(lastTagIndex + 1, iend);
                        content = new StringBuffer(
                                "<" + tagname + ">\n" + content.toString() + "</" + tagname + ">");
                    } else {
                        throw new EngineException("Malformed XML file");
                    }
                } else {
                    content.append(sbuf.substring(lastTagIndex));

                    if (isUTF8) {
                        String before = sbuf.substring(0, lastTagIndex);
                        lastTagIndex = before.getBytes(enc).length;
                    }
                }
                fc.write(ByteBuffer.wrap(content.toString().getBytes(enc)), pos + lastTagIndex);
            } finally {
                if (randomAccessFile != null) {
                    randomAccessFile.close();
                }
            }
        } catch (IOException e) {
            throw new EngineException("Unable to write to xml file", e);
        } finally {
            Engine.theApp.filePropertyManager.releaseMutex(fullPathName);
        }
    }
}

From source file:com.linkedin.haivvreo.AvroDeserializer.java

private Object deserializeList(Object datum, Schema recordSchema, ListTypeInfo columnType)
        throws HaivvreoException {
    // Need to check the original schema to see if this is actually a Fixed.
    if (recordSchema.getType().equals(Schema.Type.FIXED)) {
        // We're faking out Hive to work through a type system impedence mismatch.  Pull out the backing array and convert to a list.
        GenericData.Fixed fixed = (GenericData.Fixed) datum;
        List<Byte> asList = new ArrayList<Byte>(fixed.bytes().length);
        for (int j = 0; j < fixed.bytes().length; j++) {
            asList.add(fixed.bytes()[j]);
        }/*from   w  w  w.ja  va2  s  . com*/
        return asList;
    } else if (recordSchema.getType().equals(Schema.Type.BYTES)) {
        // This is going to be slow... hold on.
        ByteBuffer bb = (ByteBuffer) datum;
        List<Byte> asList = new ArrayList<Byte>(bb.capacity());
        byte[] array = bb.array();
        for (int j = 0; j < array.length; j++) {
            asList.add(array[j]);
        }
        return asList;
    } else { // An actual list, deser its values
        List listData = (List) datum;
        Schema listSchema = recordSchema.getElementType();
        List<Object> listContents = new ArrayList<Object>(listData.size());
        for (Object obj : listData) {
            listContents.add(worker(obj, listSchema, columnType.getListElementTypeInfo()));
        }
        return listContents;
    }
}

From source file:io.warp10.quasar.encoder.QuasarTokenEncoder.java

public String getTokenIdent(String token, byte[] tokenSipHashkey) {
    long ident = SipHashInline.hash24_palindromic(tokenSipHashkey, token.getBytes());

    ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
    buffer.order(ByteOrder.BIG_ENDIAN);
    buffer.putLong(ident);/*from   www. ja v a  2s . c  om*/
    return Hex.encodeHexString(buffer.array());
}

From source file:com.l2jfree.loginserver.network.L2Client.java

@Override
public boolean decrypt(ByteBuffer buf, int size) {
    boolean ret = false;
    try {//from   w  w  w. j a v  a 2 s.c  om
        ret = getLoginCrypt().decrypt(buf.array(), buf.position(), size);
    } catch (IOException e) {
        e.printStackTrace();
        closeNow();
        return false;
    }

    if (!ret) {
        byte[] dump = new byte[size];
        System.arraycopy(buf.array(), buf.position(), dump, 0, size);
        _log.warn("Wrong checksum from client: " + toString());
        closeNow();
    }

    return ret;
}

From source file:de.hofuniversity.iisys.neo4j.websock.query.encoding.safe.TSafeDeflateJsonQueryHandler.java

@Override
public WebsockQuery decode(ByteBuffer buff) throws DecodeException {
    WebsockQuery query = null;/*from w w w.j a  va  2  s.  c om*/

    try {
        //decompress
        final byte[] incoming = buff.array();
        final Inflater inflater = new Inflater(true);
        inflater.setInput(incoming);

        int read = 0;
        int totalSize = 0;
        final List<byte[]> buffers = new LinkedList<byte[]>();

        final byte[] buffer = new byte[BUFFER_SIZE];
        read = inflater.inflate(buffer);
        while (read > 0) {
            totalSize += read;
            buffers.add(Arrays.copyOf(buffer, read));
            read = inflater.inflate(buffer);
        }

        final byte[] data = fuse(buffers, totalSize).array();
        final JSONObject obj = new JSONObject(new String(data));

        if (fDebug) {
            fTotalBytesIn += incoming.length;
            fLogger.log(Level.FINEST, "received compressed JSON message: " + incoming.length + " bytes\n"
                    + "total bytes received: " + fTotalBytesIn);
        }

        query = JsonConverter.fromJson(obj);
    } catch (Exception e) {
        e.printStackTrace();
        throw new DecodeException(buff, "failed to decode JSON", e);
    }

    return query;
}

From source file:com.codeabovelab.dm.common.security.token.SignedTokenServiceBackend.java

@Override
public TokenData createToken(TokenConfiguration config) {
    final long creationTime = System.currentTimeMillis();

    byte[] serverSecret = computeServerSecretApplicableAt(creationTime);
    byte[] content = contentPack(creationTime, generateRandom(), serverSecret,
            Utf8.encode(pack(config.getUserName(), config.getDeviceHash())));

    byte[] sign = sign(content);
    ByteBuffer buffer = ByteBuffer.allocate(1 + sign.length + 1 + content.length);
    store(buffer, content);//from  w  w w.  j  a v a  2s  .com
    store(buffer, sign);
    String key = base32.encodeAsString(buffer.array());

    return new TokenDataImpl(creationTime, TokenUtils.getKeyWithTypeAndToken(TYPE, key), config.getUserName(),
            config.getDeviceHash());
}

From source file:com.cloudera.recordbreaker.hive.borrowed.AvroDeserializer.java

private Object deserializeList(Object datum, Schema recordSchema, ListTypeInfo columnType)
        throws AvroSerdeException {
    // Need to check the original schema to see if this is actually a Fixed.
    if (recordSchema.getType().equals(Schema.Type.FIXED)) {
        // We're faking out Hive to work through a type system impedence mismatch.
        // Pull out the backing array and convert to a list.
        GenericData.Fixed fixed = (GenericData.Fixed) datum;
        List<Byte> asList = new ArrayList<Byte>(fixed.bytes().length);
        for (int j = 0; j < fixed.bytes().length; j++) {
            asList.add(fixed.bytes()[j]);
        }/*from w  ww  . ja  v  a  2 s . com*/
        return asList;
    } else if (recordSchema.getType().equals(Schema.Type.BYTES)) {
        // This is going to be slow... hold on.
        ByteBuffer bb = (ByteBuffer) datum;
        List<Byte> asList = new ArrayList<Byte>(bb.capacity());
        byte[] array = bb.array();
        for (int j = 0; j < array.length; j++) {
            asList.add(array[j]);
        }
        return asList;
    } else { // An actual list, deser its values
        List listData = (List) datum;
        Schema listSchema = recordSchema.getElementType();
        List<Object> listContents = new ArrayList<Object>(listData.size());
        for (Object obj : listData) {
            listContents.add(worker(obj, listSchema, columnType.getListElementTypeInfo()));
        }
        return listContents;
    }
}

From source file:co.cask.cdap.client.rest.RestStreamWriter.java

@Override
public ListenableFuture<Void> write(ByteBuffer buffer, Map<String, String> headers)
        throws IllegalArgumentException {
    Preconditions.checkArgument(buffer != null, "ByteBuffer parameter is null.");
    HttpEntity content;/*www  .  j  a v a  2  s. c  om*/
    if (buffer.hasArray()) {
        content = new ByteArrayEntity(buffer.array(), buffer.arrayOffset() + buffer.position(),
                buffer.remaining());
    } else {
        byte[] bytes = new byte[buffer.remaining()];
        buffer.get(bytes);
        content = new ByteArrayEntity(bytes);
    }
    return write(content, headers);
}

From source file:com.l2jfree.loginserver.network.L2Client.java

@Override
public boolean encrypt(ByteBuffer buf, int size) {
    final int offset = buf.position();
    try {//from  w ww .j a v a 2 s .  c o m
        size = getLoginCrypt().encrypt(buf.array(), offset, size);
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }

    buf.position(offset + size);
    return true;
}

From source file:kilim.http.HttpRequest.java

public void dumpBuffer(ByteBuffer buffer) {
    byte[] ba = buffer.array();
    int len = buffer.position();
    StringBuilder print = new StringBuilder();
    for (int i = 0; i < len; i++) {
        print.append((char) ba[i]);
    }//from   ww  w  . j  a  v a 2s. co m
    log.debug(print);
}