Example usage for java.nio ByteBuffer clear

List of usage examples for java.nio ByteBuffer clear

Introduction

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

Prototype

public final Buffer clear() 

Source Link

Document

Clears this buffer.

Usage

From source file:org.restcomm.connect.http.filters.FileCacheServlet.java

/**
 * Stream the given input to the given output via NIO {@link Channels} and a
 * directly allocated NIO {@link ByteBuffer}. Both the input and output
 * streams will implicitly be closed after streaming, regardless of whether
 * an exception is been thrown or not./*from w  ww  .j ava2 s .co m*/
 *
 * @param input The input stream.
 * @param output The output stream.
 * @param bufferSize
 * @return The length of the written bytes.
 * @throws IOException When an I/O error occurs.
 */
public static long stream(InputStream input, OutputStream output, int bufferSize) throws IOException {
    try (ReadableByteChannel inputChannel = Channels.newChannel(input);
            WritableByteChannel outputChannel = Channels.newChannel(output)) {
        ByteBuffer buffer = ByteBuffer.allocateDirect(bufferSize);
        long size = 0;

        while (inputChannel.read(buffer) != -1) {
            buffer.flip();
            size += outputChannel.write(buffer);
            buffer.clear();
        }

        return size;
    }
}

From source file:com.cloudera.flume.handlers.thrift.ThriftEventAdaptor.java

/**
 * This makes a thrift compatible copy of the event. It is here to encapsulate
 * future changes to the Event/ThriftFlumeEvent interface
 */// w  ww.ja v  a2s  .c  o  m
public static ThriftFlumeEvent convert(Event e) {
    ThriftFlumeEvent evt = new ThriftFlumeEvent();
    evt.timestamp = e.getTimestamp();
    evt.priority = convert(e.getPriority());
    ByteBuffer buf = ByteBuffer.wrap(e.getBody());
    evt.body = buf;
    evt.nanos = e.getNanos();
    evt.host = e.getHost();

    Map<String, byte[]> tempMap = e.getAttrs();
    Map<String, ByteBuffer> returnMap = new HashMap<String, ByteBuffer>();
    for (String key : tempMap.keySet()) {
        buf.clear();
        buf = ByteBuffer.wrap(tempMap.get(key));
        returnMap.put(key, buf);
    }

    evt.fields = returnMap;
    return evt;
}

From source file:divconq.util.IOUtil.java

public static Memory readEntireFileToMemory(Path file) {
    try (FileChannel ch = FileChannel.open(file, StandardOpenOption.READ)) {
        Memory mem = new Memory(); // TODO improve mem to read right from channel...

        ByteBuffer bb = ByteBuffer.allocate(4096);

        int amt = ch.read(bb);

        while (amt != -1) {
            bb.flip();//from   w  w  w  .  j  ava 2  s. c o m
            mem.write(bb);
            bb.clear();
            amt = ch.read(bb);
        }

        mem.setPosition(0);

        return mem;
    } catch (IOException x) {
    }

    return null;
}

From source file:com.log4ic.compressor.utils.FileUtils.java

/**
 * ?/*from  w w  w .  java 2 s.  c  om*/
 *
 * @param fileInputStream
 * @return
 */
public static String readFile(FileInputStream fileInputStream) throws IOException {
    ByteBuffer buffer = ByteBuffer.allocate(1024);
    StringBuffer contentBuffer = new StringBuffer();
    Charset charset = null;
    CharsetDecoder decoder = null;
    CharBuffer charBuffer = null;
    try {
        FileChannel channel = fileInputStream.getChannel();
        while (true) {
            buffer.clear();
            int pos = channel.read(buffer);
            if (pos == -1) {
                break;
            }
            buffer.flip();
            charset = Charset.forName("UTF-8");
            decoder = charset.newDecoder();
            charBuffer = decoder.decode(buffer);
            contentBuffer.append(charBuffer.toString());
        }
    } finally {
        if (fileInputStream != null) {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return contentBuffer.toString();
}

From source file:android.framework.util.jar.Manifest.java

private static void writeEntry(OutputStream os, Attributes.Name name, String value, CharsetEncoder encoder,
        ByteBuffer bBuf) throws IOException {
    String nameString = name.getName();
    os.write(nameString.getBytes(Charsets.US_ASCII));
    os.write(VALUE_SEPARATOR);/*from  w ww. j a  va 2  s  .c  o m*/

    encoder.reset();
    bBuf.clear().limit(LINE_LENGTH_LIMIT - nameString.length() - 2);

    CharBuffer cBuf = CharBuffer.wrap(value);

    while (true) {
        CoderResult r = encoder.encode(cBuf, bBuf, true);
        if (CoderResult.UNDERFLOW == r) {
            r = encoder.flush(bBuf);
        }
        os.write(bBuf.array(), bBuf.arrayOffset(), bBuf.position());
        os.write(LINE_SEPARATOR);
        if (CoderResult.UNDERFLOW == r) {
            break;
        }
        os.write(' ');
        bBuf.clear().limit(LINE_LENGTH_LIMIT - 1);
    }
}

From source file:com.discovery.darchrow.io.IOWriteUtil.java

/**
 * NIO API ?? ().// w w  w . j a  va  2s.c om
 *
 * @param bufferLength
 *            the buffer length
 * @param inputStream
 *            the input stream
 * @param outputStream
 *            the output stream
 * @since 1.0.8
 * @since jdk1.4
 */
private static void writeUseNIO(int bufferLength, InputStream inputStream, OutputStream outputStream) {
    int i = 0;
    int sumSize = 0;
    int j = 0;

    ///2 
    //As creme de la creme with regard to performance, you could use NIO Channels and ByteBuffer. 

    ReadableByteChannel readableByteChannel = Channels.newChannel(inputStream);
    WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);

    ByteBuffer byteBuffer = ByteBuffer.allocate(bufferLength);

    try {
        while (readableByteChannel.read(byteBuffer) != -1) {
            byteBuffer.flip();
            j = writableByteChannel.write(byteBuffer);
            sumSize += j;
            byteBuffer.clear();
            i++;
        }

        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Write data over,sumSize:[{}],bufferLength:[{}],loopCount:[{}]",
                    FileUtil.formatSize(sumSize), bufferLength, i);
        }
    } catch (IOException e) {
        throw new UncheckedIOException(e);
    } finally {
        IOUtils.closeQuietly(outputStream);
        IOUtils.closeQuietly(writableByteChannel);
        IOUtils.closeQuietly(inputStream);
        IOUtils.closeQuietly(readableByteChannel);
    }
}

From source file:com.serotonin.bacnet4j.util.sero.StreamUtils.java

public static void transfer(InputStream in, SocketChannel out) throws IOException {
    byte[] buf = new byte[1024];
    ByteBuffer bbuf = ByteBuffer.allocate(1024);
    int len;/* w w w.  ja v a 2  s .  com*/
    while ((len = in.read(buf)) != -1) {
        bbuf.put(buf, 0, len);
        bbuf.flip();
        while (bbuf.remaining() > 0)
            out.write(bbuf);
        bbuf.clear();
    }
}

From source file:org.shaman.terrain.vegetation.ImpositorCreator.java

public static void convertScreenShot(ByteBuffer bgraBuf, BufferedImage out) {
    WritableRaster wr = out.getRaster();
    DataBufferByte db = (DataBufferByte) wr.getDataBuffer();

    byte[] cpuArray = db.getData();

    // copy native memory to java memory
    bgraBuf.clear();
    bgraBuf.get(cpuArray);/*from   w w w .  j ava  2  s. c  o  m*/
    bgraBuf.clear();

    int width = wr.getWidth();
    int height = wr.getHeight();

    // flip the components the way AWT likes them

    // calcuate half of height such that all rows of the array are written to
    // e.g. for odd heights, write 1 more scanline
    int heightdiv2ceil = height % 2 == 1 ? (height / 2) + 1 : height / 2;
    for (int y = 0; y < heightdiv2ceil; y++) {
        for (int x = 0; x < width; x++) {
            int inPtr = (y * width + x) * 4;
            int outPtr = ((height - y - 1) * width + x) * 4;

            byte b1 = cpuArray[inPtr + 0];
            byte g1 = cpuArray[inPtr + 1];
            byte r1 = cpuArray[inPtr + 2];
            byte a1 = cpuArray[inPtr + 3];

            byte b2 = cpuArray[outPtr + 0];
            byte g2 = cpuArray[outPtr + 1];
            byte r2 = cpuArray[outPtr + 2];
            byte a2 = cpuArray[outPtr + 3];

            cpuArray[outPtr + 0] = a1;
            cpuArray[outPtr + 1] = r1;//b1;
            cpuArray[outPtr + 2] = g1;
            cpuArray[outPtr + 3] = b1;//r1;

            cpuArray[inPtr + 0] = a2;
            cpuArray[inPtr + 1] = r2;//b2;
            cpuArray[inPtr + 2] = g2;
            cpuArray[inPtr + 3] = b2;//r2;
        }
    }
}

From source file:password.pwm.util.secure.SecureEngine.java

public static String hash(final File file, final PwmHashAlgorithm hashAlgorithm)
        throws IOException, PwmUnrecoverableException {
    FileInputStream fileInputStream = null;
    try {//w  w  w  .ja  va  2s .c  o  m
        final MessageDigest messageDigest = MessageDigest.getInstance(hashAlgorithm.getAlgName());
        fileInputStream = new FileInputStream(file);
        final FileChannel fileChannel = fileInputStream.getChannel();
        final ByteBuffer byteBuffer = ByteBuffer.allocateDirect(1024 * 8);

        while (fileChannel.read(byteBuffer) > 0) {
            byteBuffer.flip();
            messageDigest.update(byteBuffer);
            byteBuffer.clear();
        }

        return JavaHelper.byteArrayToHexString(messageDigest.digest());

    } catch (NoSuchAlgorithmException | IOException e) {
        final String errorMsg = "unexpected error during file hash operation: " + e.getMessage();
        final ErrorInformation errorInformation = new ErrorInformation(PwmError.ERROR_CRYPT_ERROR, errorMsg);
        throw new PwmUnrecoverableException(errorInformation);
    } finally {
        IOUtils.closeQuietly(fileInputStream);
    }
}

From source file:net.vexelon.myglob.utils.Utils.java

/**
 * Reads an input stream into a byte array
 * @param source// w w  w .j av  a  2s. c o  m
 * @return Byte array of input stream data
 * @throws IOException
 */
public static byte[] read(InputStream source) throws IOException {
    ReadableByteChannel srcChannel = Channels.newChannel(source);
    ByteArrayOutputStream baos = new ByteArrayOutputStream(
            source.available() > 0 ? source.available() : BUFFER_PAGE_SIZE);
    WritableByteChannel destination = Channels.newChannel(baos);

    try {
        ByteBuffer buffer = ByteBuffer.allocate(BUFFER_PAGE_SIZE);
        while (srcChannel.read(buffer) > 0) {
            buffer.flip();
            while (buffer.hasRemaining()) {
                destination.write(buffer);
            }
            buffer.clear();
        }
        return baos.toByteArray();
    } catch (IOException e) {
        throw e;
    } finally {
        try {
            if (srcChannel != null)
                srcChannel.close();
        } catch (IOException e) {
        }
        try {
            if (source != null)
                source.close();
        } catch (IOException e) {
        }
        try {
            if (destination != null)
                destination.close();
        } catch (IOException e) {
        }
    }
}