Example usage for java.nio CharBuffer allocate

List of usage examples for java.nio CharBuffer allocate

Introduction

In this page you can find the example usage for java.nio CharBuffer allocate.

Prototype

public static CharBuffer allocate(int capacity) 

Source Link

Document

Creates a char buffer based on a newly allocated char array.

Usage

From source file:com.cloudbees.jenkins.support.filter.FilteredWriterTest.java

@Issue("JENKINS-21670")
@Test//from   w w  w . j a  va2  s .c o m
public void shouldSupportLinesLongerThanDefaultBufferSize() throws Exception {
    CharBuffer input = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY * 10);
    for (int i = 0; i < input.capacity(); i++) {
        input.put('+');
    }
    input.flip();
    CharSequenceReader reader = new CharSequenceReader(input);
    ContentFilter filter = s -> s.replace('+', '-');
    StringWriter output = new StringWriter();
    FilteredWriter writer = new FilteredWriter(output, filter);

    IOUtils.copy(reader, writer);
    assertThat(output.toString()).isEmpty();

    writer.flush();

    assertThat(output.toString()).isNotEmpty().matches("^-+$");

}

From source file:com.metawiring.load.generators.LoremExtractGenerator.java

private CharBuffer loadLoremIpsum() {
    InputStream stream = LoremExtractGenerator.class.getClassLoader()
            .getResourceAsStream("data/lorem_ipsum_full.txt");
    if (stream == null) {
        throw new RuntimeException("lorem_ipsum_full.txt was missing.");
    }//w  ww.  ja v a2  s  .c om

    CharBuffer image;
    try {
        InputStreamReader isr = new InputStreamReader(stream);
        image = CharBuffer.allocate(1024 * 1024);
        isr.read(image);
        isr.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    image.flip();

    return image.asReadOnlyBuffer();

}

From source file:gdv.xport.io.RecyclingInputStreamReaderTest.java

/**
 * Test-Methode fuer {@link RecyclingInputStreamReader#skip(long)} und
 * {@link RecyclingInputStreamReader#read(CharBuffer)}.
 *
 * @throws IOException Signals that an I/O exception has occurred.
 *//*w w w  .j  a  v  a2  s  . co m*/
@Test
public void testSkip() throws IOException {
    RecyclingInputStreamReader reader = new RecyclingInputStreamReader(istream, "ASCII");
    try {
        reader.skip(1L);
        CharBuffer cbuf = CharBuffer.allocate(HELLO.length());
        reader.read(cbuf);
        assertEquals(HELLO.substring(1), new String(cbuf.array()).trim());
    } finally {
        reader.close();
    }
}

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

/**
 * Creates or re-uses a {@link CharBuffer} that has a minimum size. Calling
 * this method multiple times with the same key will always return the
 * same buffer, as long as it has the minimum size and is marked to be
 * re-used. Buffers that are allowed to be re-used should be released using
 * {@link #releaseCharBuffer(Key, CharBuffer)}.
 * @param key the buffer's identifier/*from   w ww .  j a  va2s  .co  m*/
 * @param minSize the minimum size
 * @return the {@link CharBuffer} instance
 */
public CharBuffer charBuffer(Key key, int minSize) {
    minSize = Math.max(minSize, GLOBAL_MIN_SIZE);

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

From source file:it.tidalwave.northernwind.frontend.ui.component.DefaultStaticHtmlFragmentViewController.java

protected void populate(final @Nonnull String htmlResourceName, final @Nonnull Map<String, String> attributes)
        throws IOException {
    final Resource htmlResource = new ClassPathResource(htmlResourceName, getClass());
    final @Cleanup Reader r = new InputStreamReader(htmlResource.getInputStream());
    final CharBuffer charBuffer = CharBuffer.allocate((int) htmlResource.contentLength());
    final int length = r.read(charBuffer);
    r.close();//  www.  j  a va 2  s  . c o m
    final String html = new String(charBuffer.array(), 0, length);

    ST template = new ST(html, '$', '$');

    for (final Entry<String, String> entry : attributes.entrySet()) {
        template = template.add(entry.getKey(), entry.getValue());
    }

    view.setContent(template.render());
}

From source file:com.cloudbees.jenkins.support.filter.FilteredOutputStreamTest.java

@Issue("JENKINS-21670")
@Test/*from   w  ww.  j  a  va2 s. c  o  m*/
public void shouldSupportLinesLargerThanDefaultBufferSize() throws IOException {
    CharBuffer input = CharBuffer.allocate(FilteredConstants.DEFAULT_DECODER_CAPACITY * 10);
    for (int i = 0; i < input.capacity(); i++) {
        input.put('*');
    }
    input.flip();
    InputStream in = new CharSequenceInputStream(input, UTF_8);
    FilteredOutputStream out = new FilteredOutputStream(testOutput, s -> s.replace('*', 'a'));

    IOUtils.copy(in, out);
    String contents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(contents).isEmpty();

    out.flush();
    contents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(contents).isNotEmpty().matches("^a+$");
}

From source file:co.cask.cdap.logging.gateway.handlers.ChunkedLogReaderCallback.java

@Override
public void close() {
    try {/*from  w  ww.j ava  2 s  .c  o m*/
        // Write the last chunk
        encodeSend(CharBuffer.allocate(0), true);
        // Flush the encoder
        CoderResult coderResult;
        do {
            coderResult = charsetEncoder.flush(chunkBuffer);
            chunkBuffer.flip();
            chunkResponder.sendChunk(ChannelBuffers.copiedBuffer(chunkBuffer));
            chunkBuffer.clear();
        } while (coderResult.isOverflow());
    } catch (IOException e) {
        // If cannot send chunks, nothing can be done (since the client closed connection).
        // Just log the error as debug.
        LOG.debug("Failed to send chunk", e);
    } finally {
        try {
            patternLayout.stop();
        } finally {
            Closeables.closeQuietly(chunkResponder);
        }
    }
}

From source file:com.metawiring.load.generators.ExtractGenerator.java

private CharBuffer loadFileData() {
    InputStream stream = null;//from  w  w  w. jav  a2  s.co m
    File onFileSystem = new File("data" + File.separator + fileName);

    if (onFileSystem.exists()) {
        try {
            stream = new FileInputStream(onFileSystem);
        } catch (FileNotFoundException e) {
            throw new RuntimeException(
                    "Unable to find file " + onFileSystem.getPath() + " after verifying that it exists.");
        }
        logger.debug("Loaded file data from " + onFileSystem.getPath());
    }

    if (stream == null) {
        stream = Thread.currentThread().getContextClassLoader().getResourceAsStream("data/" + fileName);
        logger.debug("Loaded file data from classpath resource " + fileName);
    }

    if (stream == null) {
        throw new RuntimeException(fileName + " was missing.");
    }

    CharBuffer image;
    try {
        InputStreamReader isr = new InputStreamReader(stream);
        image = CharBuffer.allocate(1024 * 1024);
        isr.read(image);
        isr.close();
    } catch (IOException e) {
        logger.error(e.getMessage());
        throw new RuntimeException(e);
    }
    image.flip();

    return image.asReadOnlyBuffer();

}

From source file:com.cloudera.sqoop.io.TestLobFile.java

private void verifyClobFile(Path p, String... expectedRecords) throws Exception {

    LobFile.Reader reader = LobFile.open(p, conf);

    int recNum = 0;

    while (reader.next()) {
        // We should have a record of the same length as the expected one.
        String expected = expectedRecords[recNum];
        assertTrue(reader.isRecordAvailable());
        assertEquals(expected.length(), reader.getRecordLen());
        Reader r = reader.readClobRecord();

        // Read in the record and assert that we got enough characters out.
        CharBuffer buf = CharBuffer.allocate(expected.length());
        int bytesRead = 0;
        while (bytesRead < expected.length()) {
            int thisRead = r.read(buf);
            LOG.info("performed read of " + thisRead + " chars");
            if (-1 == thisRead) {
                break;
            }/*from   w w  w . j av  a  2s . c  om*/

            bytesRead += thisRead;
        }

        LOG.info("Got record of " + bytesRead + " chars");
        assertEquals(expected.length(), bytesRead);
        char[] charData = buf.array();
        String finalRecord = new String(charData);
        assertEquals(expected, finalRecord);

        recNum++;
    }

    // Check that we got everything.
    assertEquals(expectedRecords.length, recNum);

    reader.close();

    try {
        reader.next();
        fail("Expected IOException calling next after close");
    } catch (IOException ioe) {
        // expected this.
    }

    // A second close shouldn't hurt anything. This should be a no-op.
    reader.close();
}

From source file:com.google.flatbuffers.Table.java

/**
 * Create a Java `String` from UTF-8 data stored inside the FlatBuffer.
 *
 * This allocates a new string and converts to wide chars upon each access,
 * which is not very efficient. Instead, each FlatBuffer string also comes with an
 * accessor based on __vector_as_bytebuffer below, which is much more efficient,
 * assuming your Java program can handle UTF-8 data directly.
 *
 * @param offset An `int` index into the Table's ByteBuffer.
 * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`.
 *///from  w  w  w .  j ava 2  s. c  o  m
protected String __string(int offset) {
    CharsetDecoder decoder = UTF8_DECODER.get();
    decoder.reset();

    offset += bb.getInt(offset);
    ByteBuffer src = bb.duplicate().order(ByteOrder.LITTLE_ENDIAN);
    int length = src.getInt(offset);
    src.position(offset + SIZEOF_INT);
    src.limit(offset + SIZEOF_INT + length);

    int required = (int) ((float) length * decoder.maxCharsPerByte());
    CharBuffer dst = CHAR_BUFFER.get();
    if (dst == null || dst.capacity() < required) {
        dst = CharBuffer.allocate(required);
        CHAR_BUFFER.set(dst);
    }

    dst.clear();

    try {
        CoderResult cr = decoder.decode(src, dst, true);
        if (!cr.isUnderflow()) {
            cr.throwException();
        }
    } catch (CharacterCodingException x) {
        throw new Error(x);
    }

    return dst.flip().toString();
}