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:com.github.neoio.net.message.staging.file.TestFileMessageStaging.java

@Test
public void test_tempWrite() {
    ByteBuffer buffer = ByteBuffer.allocate(1024);

    buffer.put("Hello World".getBytes());
    buffer.flip();/* ww  w .j ava  2s. c  o m*/
    staging.writeTempWriteBytes(buffer);
    Assert.assertTrue(staging.hasTempWriteBytes());

    buffer.clear();
    staging.readTempWriteBytes(buffer);
    Assert.assertEquals("Hello World",
            new String(ArrayUtils.subarray(buffer.array(), 0, "Hello World".getBytes().length)));
    staging.resetTempWriteBytes();

    Assert.assertFalse(staging.hasTempWriteBytes());
}

From source file:de.undercouch.bson4jackson.io.StaticBuffers.java

/**
 * @see #charBuffer(Key, int)/*  w  w  w . j  a v  a2 s  .  co  m*/
 */
public ByteBuffer byteBuffer(Key key, int minSize) {
    minSize = Math.max(minSize, GLOBAL_MIN_SIZE);

    ByteBuffer r = _byteBuffers[key.ordinal()];
    if (r == null || r.capacity() < minSize) {
        r = ByteBuffer.allocate(minSize);
    } else {
        _byteBuffers[key.ordinal()] = null;
        r.clear();
    }
    return r;
}

From source file:org.cloudata.core.commitlog.pipe.Bulk.java

public void clear() {
    ByteBuffer buf = bufferList.remove(bufferList.size() - 1);
    buf.clear();

    if (bufferList.isEmpty() == false) {
        LOG.debug("bulk [" + this + "] clear, " + bufferList.size() + " is returned");
        BufferPool.singleton().returnBuffer(bufferList.toArray(new ByteBuffer[0]));
    }/*  www.  j  a v  a  2 s.  co  m*/

    bufferList.clear();
    bufferList.add(buf);

    currentReadBufIndex = 0;
    currentWriteBufIndex = 0;
    writtenPos = 0;
    readingHeaderDone = false;
    headerAndPayloadSize = 0;
    totalNumRead = 0;
    txId = null;
    seq = -1;
    totalNumWritten = 0;
    readBytesLength = 4;
    dirNameBytes = null;
}

From source file:siddur.solidtrust.fault.FaultController.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file, @RequestParam("version") int v,
        Model model, HttpSession session) throws Exception {

    IFaultPersister persister = getPersister(v);

    //upload/*from   w ww  . j  a va 2  s . c  o  m*/
    log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize());
    File temp = File.createTempFile("data", ".csv");
    log4j.info("Will save to " + temp.getAbsolutePath());

    InputStream in = null;
    FileOutputStream fout = null;

    try {
        fout = new FileOutputStream(temp);
        FileChannel fcout = fout.getChannel();

        in = file.getInputStream();
        ReadableByteChannel cin = Channels.newChannel(in);

        ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
        while (true) {
            buf.clear();

            int r = cin.read(buf);

            if (r == -1) {
                break;
            }

            buf.flip();
            fcout.write(buf);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
    log4j.info("Uploading complete");

    //fields
    BufferedReader br = null;
    int[] orders;
    try {
        in = new FileInputStream(temp);
        br = new BufferedReader(new InputStreamReader(in));

        //first line for fields
        String firstLine = br.readLine();
        orders = persister.validateTitle(firstLine);

        //persist
        persister.parseAndSave(br, orders, persister);
    } finally {
        if (br != null) {
            br.close();
        }
    }

    return "redirect:upload.html";
}

From source file:eu.stratosphere.arraymodel.io.StringInputFormat.java

public boolean readRecord(Value[] target, byte[] bytes, int offset, int numBytes) {
    StringValue str = this.theString;

    if (this.ascii) {
        str.setValueAscii(bytes, offset, numBytes);
    } else {// www  . j  a va  2s  .co  m
        ByteBuffer byteWrapper = this.byteWrapper;
        if (bytes != byteWrapper.array()) {
            byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
            this.byteWrapper = byteWrapper;
        }
        byteWrapper.clear();
        byteWrapper.position(offset);
        byteWrapper.limit(offset + numBytes);

        try {
            CharBuffer result = this.decoder.decode(byteWrapper);
            str.setValue(result);
        } catch (CharacterCodingException e) {
            byte[] copy = new byte[numBytes];
            System.arraycopy(bytes, offset, copy, 0, numBytes);
            LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
            return false;
        }
    }

    target[0] = str;
    return true;
}

From source file:siddur.solidtrust.newprice2.Newprice2Controller.java

@RequestMapping(value = "/upload", method = RequestMethod.POST)
public String handleFormUpload(@RequestParam("file") MultipartFile file, Model model, HttpSession session)
        throws IOException {

    //upload// w  w  w . j  a  v a 2s . c  o m
    log4j.info("Start uploading file: " + file.getName() + " with size: " + file.getSize());
    File temp = File.createTempFile("data", ".csv");
    log4j.info("Will save to " + temp.getAbsolutePath());

    InputStream in = null;
    FileOutputStream fout = null;

    try {
        fout = new FileOutputStream(temp);
        FileChannel fcout = fout.getChannel();

        in = file.getInputStream();
        ReadableByteChannel cin = Channels.newChannel(in);

        ByteBuffer buf = ByteBuffer.allocate(1024 * 8);
        while (true) {
            buf.clear();

            int r = cin.read(buf);

            if (r == -1) {
                break;
            }

            buf.flip();
            fcout.write(buf);
        }
    } finally {
        if (in != null) {
            in.close();
        }
        if (fout != null) {
            fout.close();
        }
    }
    FileStatus fs = new FileStatus();
    fs.setFile(temp);
    log4j.info("Uploading complete");

    //fields
    BufferedReader br = null;
    int[] orders;
    String[] fields;
    try {
        in = new FileInputStream(temp);
        br = new BufferedReader(new InputStreamReader(in));

        //first line for fields
        String firstLine = br.readLine();
        fields = StringUtils.split(firstLine, ";");
        ;
        orders = new int[fields.length];
        for (int i = 0; i < orders.length; i++) {
            orders[i] = ArrayUtils.indexOf(FIELDS, fields[i].trim());
        }

        //count
        while (br.readLine() != null) {
            fs.next();
        }
    } finally {
        if (br != null) {
            br.close();
        }
    }

    fs.flip();
    log4j.info("Total rows: " + fs.getTotalRow());

    //persist
    carService.saveCars(fs, orders, carService);
    return "redirect:/v2/upload.html";
}

From source file:eu.stratosphere.pact.array.io.StringInputFormat.java

public boolean readRecord(Value[] target, byte[] bytes, int offset, int numBytes) {
    PactString str = this.theString;

    if (this.ascii) {
        str.setValueAscii(bytes, offset, numBytes);
    } else {//from w  w w  .  j  a v a 2s  .  c o  m
        ByteBuffer byteWrapper = this.byteWrapper;
        if (bytes != byteWrapper.array()) {
            byteWrapper = ByteBuffer.wrap(bytes, 0, bytes.length);
            this.byteWrapper = byteWrapper;
        }
        byteWrapper.clear();
        byteWrapper.position(offset);
        byteWrapper.limit(offset + numBytes);

        try {
            CharBuffer result = this.decoder.decode(byteWrapper);
            str.setValue(result);
        } catch (CharacterCodingException e) {
            byte[] copy = new byte[numBytes];
            System.arraycopy(bytes, offset, copy, 0, numBytes);
            LOG.warn("Line could not be encoded: " + Arrays.toString(copy), e);
            return false;
        }
    }

    target[0] = str;
    return true;
}

From source file:SelfClassLoader.java

private byte[] loadClassBytes(String className) throws ClassNotFoundException {
    try {//from w  w  w  .jav  a  2s .  c om
        String classFile = getClassFile(className);
        FileInputStream fis = new FileInputStream(classFile);
        FileChannel fileC = fis.getChannel();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        WritableByteChannel outC = Channels.newChannel(baos);
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            int i = fileC.read(buffer);
            if (i == 0 || i == -1) {
                break;
            }
            buffer.flip();
            outC.write(buffer);
            buffer.clear();
        }
        fis.close();
        return baos.toByteArray();
    } catch (IOException fnfe) {
        throw new ClassNotFoundException(className);
    }
}

From source file:com.turbospaces.serialization.PropertiesSerializer.java

/**
 * read entity from byte buffer stream (and remember the property values as array)
 * /*www  .  j  a v a  2  s . com*/
 * @param buffer
 *            byte array pointer
 * @return de-serialized entry
 */
public SerializationEntry readToSerializedEntry(final ByteBuffer buffer) {
    final Object values[] = new Object[cachedProperties.length];
    for (int i = 0, n = cachedProperties.length; i < n; i++)
        values[i] = DecoratedKryo.readPropertyValue(kryo, cachedProperties[i], buffer);
    buffer.clear();
    return new SerializationEntry(buffer,
            entityMetadata.setBulkPropertyValues(entityMetadata.newInstance(), values), values);
}

From source file:org.apache.nifi.io.nio.consumer.AbstractStreamConsumer.java

@Override
public final void process() throws IOException {
    if (isConsumerFinished()) {
        return;/*from w  ww.j  a v a2  s . c om*/
    }
    if (streamEnded.get() && filledBuffers.isEmpty()) {
        consumerEnded.set(true);
        onConsumerDone();
        return;
    }
    final ByteBuffer buffer = filledBuffers.poll();
    if (buffer != null) {
        final int bytesToProcess = buffer.remaining();
        try {
            processBuffer(buffer);
        } finally {
            buffer.clear();
            bufferPool.returnBuffer(buffer, bytesToProcess);
        }
    }
}