Example usage for java.nio CharBuffer array

List of usage examples for java.nio CharBuffer array

Introduction

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

Prototype

public final char[] array() 

Source Link

Document

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

Usage

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

private void loadTemplate() throws IOException {
    // FIXME: this should be done only once...
    Resource resource = null;/*  w  w  w . j a  v a2 s.c  o  m*/

    for (Class<?> clazz = getClass(); clazz.getSuperclass() != null; clazz = clazz.getSuperclass()) {
        final String templateName = clazz.getSimpleName() + ".txt";
        resource = new ClassPathResource(templateName, clazz);

        if (resource.exists()) {
            break;
        }
    }

    try {
        if (resource == null) {
            throw new FileNotFoundException();
        }

        final @Cleanup Reader r = new InputStreamReader(resource.getInputStream());
        final CharBuffer charBuffer = CharBuffer.allocate((int) resource.contentLength());
        final int length = r.read(charBuffer);
        r.close();
        template = new String(charBuffer.array(), 0, length);
    } catch (FileNotFoundException e) // no specific template, fallback
    {
        log.warn("No template for {}, using default", getClass().getSimpleName());
        template = "$content$\n";
    }
}

From source file:com.pnf.plugin.pdf.XFAParser.java

public void parse(byte[] xmlContent) throws ParserConfigurationException, SAXException, IOException {
    CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();
    decoder.onMalformedInput(CodingErrorAction.REPLACE);
    decoder.onUnmappableCharacter(CodingErrorAction.REPLACE);
    CharBuffer parsed = decoder.decode(ByteBuffer.wrap(xmlContent));

    SAXParserFactory factory = SAXParserFactory.newInstance();
    SAXParser parser = factory.newSAXParser();

    try (@SuppressWarnings("deprecation")
    InputStream is = new ReaderInputStream(new CharArrayReader(parsed.array()))) {
        parser.parse(is, xfa);/*from  w w w . ja  va 2 s  .  c  o m*/
    } catch (Exception e) {
        logger.catching(e);
        logger.error("Error while parsing XFA content");
    }
}

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

/**
 * Run a test where we read only a fraction of the first record,
 * but then read the second record completely. Verify that we
 * can re-align on a record boundary correctly. This test requires
 * at least 3 records./*from ww w . j  a  v a 2s  . c o m*/
 * @param p the path to the file to create.
 * @param firstLine the first line of the first reord
 * @param records All of the records to write to the file.
 */
private void runLineAndRecordTest(Path p, String firstLine, String... records) throws Exception {

    assertTrue("This test requires 3+ records", records.length > 2);

    writeClobFile(p, null, records);

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

    // We should not yet be aligned.
    assertFalse(reader.isRecordAvailable());
    assertTrue(reader.next());
    // Now we should be.
    assertTrue(reader.isRecordAvailable());

    // Read just one line from the record.
    Reader r = reader.readClobRecord();
    BufferedReader br = new BufferedReader(r);
    String line = br.readLine();
    assertEquals(firstLine, line);

    br.close();
    r.close();

    // We should no longer be aligned on a record start.
    assertFalse(reader.isRecordAvailable());

    // We should now be able to get to record two.
    assertTrue(reader.next());

    // This should be nicely aligned even if the first record was not
    // completely consumed by a client.
    r = reader.readClobRecord();
    CharBuffer buf = CharBuffer.allocate(records[1].length());
    r.read(buf);
    r.close();
    char[] chars = buf.array();
    String s = new String(chars);
    assertEquals(records[1], s);

    // Close the reader before we consume the entire file. 
    reader.close();
    assertFalse(reader.isRecordAvailable());
}

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

public void testSeekToRecord() throws Exception {
    // Seek past the first two records and read the third.

    Path p = new Path(TEMP_BASE_DIR, "seek.lob");
    String[] records = { "this is the first record!", "here comes record number two. It is a bit longer.",
            "this is the third record. we can read it.", };

    // Write the file and memorize when the third record starts.
    LobFile.Writer writer = LobFile.create(p, conf, true);

    int recNum = 0;
    long rec3Start = 0;
    for (String r : records) {
        Writer w = writer.writeClobRecord(r.length());
        w.write(r);//from w  w w.  j  a va2s .c  o m
        w.close();
        writer.finishRecord();
        if (recNum == 1) {
            rec3Start = writer.tell();
            LOG.info("Record three start: " + rec3Start);
        }
        recNum++;
    }

    writer.close();

    // Now reopen the file for read, seek to the third record, and get it.
    LobFile.Reader reader = LobFile.open(p, conf);
    reader.seek(rec3Start);
    assertTrue(reader.next());
    assertTrue(reader.isRecordAvailable());
    assertEquals(rec3Start, reader.getRecordOffset());

    Reader r = reader.readClobRecord();
    CharBuffer buf = CharBuffer.allocate(records[2].length());
    r.read(buf);
    r.close();
    char[] chars = buf.array();
    String s = new String(chars);
    assertEquals(records[2], s);

    r.close();
    reader.close();
}

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

/** Verifies that the next record in the LobFile is the expected one. */
private void verifyNextRecord(LobFile.Reader reader, long expectedId, String expectedRecord) throws Exception {
    assertTrue(reader.next());/*from   w w w  .ja v  a2 s.c  om*/
    assertTrue(reader.isRecordAvailable());
    assertEquals(expectedId, reader.getRecordId());

    Reader r = reader.readClobRecord();
    CharBuffer buf = CharBuffer.allocate(expectedRecord.length());
    int bytesRead = 0;
    while (bytesRead < expectedRecord.length()) {
        int thisRead = r.read(buf);
        if (-1 == thisRead) {
            break;
        }

        bytesRead += thisRead;
    }

    LOG.info("Got record of " + bytesRead + " chars");
    assertEquals(expectedRecord.length(), bytesRead);

    char[] charData = buf.array();
    String finalRecord = new String(charData);
    assertEquals(expectedRecord, finalRecord);
}

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;
            }//  w  w w . ja  va 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:ch.entwine.weblounge.contentrepository.impl.AbstractContentRepository.java

/**
 * Returns the resource uri or <code>null</code> if no resource id and/or path
 * could be found on the specified document. This method is intended to serve
 * as a utility method when importing resources.
 * /*from ww w . j a  va2  s.  c  o  m*/
 * @param site
 *          the resource uri
 * @param contentUrl
 *          location of the resource file
 * @return the resource uri
 */
protected ResourceURI loadResourceURI(Site site, URL contentUrl) throws IOException {

    InputStream is = null;
    InputStreamReader reader = null;
    try {
        is = new BufferedInputStream(contentUrl.openStream());
        reader = new InputStreamReader(is);
        CharBuffer buf = CharBuffer.allocate(1024);
        reader.read(buf);
        String s = new String(buf.array());
        s = s.replace('\n', ' ');
        Matcher m = resourceHeaderRegex.matcher(s);
        if (m.matches()) {
            long version = ResourceUtils.getVersion(m.group(4));
            return new ResourceURIImpl(m.group(1), site, m.group(3), m.group(2), version);
        }
        return null;
    } finally {
        if (reader != null)
            reader.close();
        IOUtils.closeQuietly(is);
    }
}

From source file:com.netscape.cmsutil.crypto.CryptoUtil.java

public static char[] bytesToChars(byte[] bytes) {
    if (bytes == null)
        return null;

    Charset charset = Charset.forName("UTF-8");
    CharBuffer charBuffer = charset.decode(ByteBuffer.wrap(bytes));
    char[] result = Arrays.copyOf(charBuffer.array(), charBuffer.limit());

    //Clear up the CharBuffer we just created
    if (charBuffer.hasArray()) {
        char[] contentsToBeErased = charBuffer.array();
        CryptoUtil.obscureChars(contentsToBeErased);
    }//from  ww  w .ja va 2s  . c o m
    return result;
}

From source file:org.alan.graph.binaryparsermaven.util.ParseZNOFiles.java

private void parseFile(File f, String dir, SchoolInterface s, Date dat) throws Exception {
    try {//from   ww  w .  j  a  v a  2  s .c  o m

        //rs
        /*
          FileWriter fileWriter = new FileWriter(dir + f.getName() + ".csv");
          CSVWriter cw = new CSVWriter(fileWriter);
                 
          */
        //rs
        int schools = 1;

        FileInputStream fis = new FileInputStream(f);

        byte[] arr = IOUtils.toByteArray(fis);

        byte[] split = new byte[] { 0x00, 0x01, 0x0a, 0x00, 0x00, 0x00 };

        int rend = 0;
        int start = 0;
        int end = 0;
        byte[] data;
        int i1 = 0;

        boolean flag = true;

        while (flag) {

            schools++;
            //System.out.println(schools);

            start = indexOf(arr, split, end);
            end = indexOf(arr, split, start + split.length);

            rend = indexOf(arr, split, end + split.length - 1);

            if (end < start) {
                end = arr.length - 1;
                flag = false;
            }

            if (Math.abs(rend - end) <= 6 && rend > 0) {
                end = rend;
            }

            data = new byte[(end - start) + 1];
            i1 = 0;
            for (int i = start; i < end; i++) {
                data[i1++] = arr[i];

            }

            String[] parsedData = parseData(data, split.length, dat);

            /* if (s == null) {
             cw.writeNext(parsedData);
             } else {*/
            Points p = new Points();
            p.setValueType(f.getName());
            p.setKoatyy(parsedData[0]);
            p.setParentKoatyy(parsedData[1]);

            CharsetDecoder utf8Decoder = Charset.forName("UTF-8").newDecoder();
            utf8Decoder.onMalformedInput(CodingErrorAction.IGNORE);
            utf8Decoder.onUnmappableCharacter(CodingErrorAction.IGNORE);
            ByteBuffer bytes = ByteBuffer.wrap(parsedData[2].getBytes());
            CharBuffer parsed = utf8Decoder.decode(bytes);
            String repl = String.valueOf(parsed.array());
            repl = repl.replaceAll("\\x00", "");

            p.setSchoolName(repl);
            p.setSchoolType(Integer.valueOf(parsedData[3]));
            p.setValue1(Double.valueOf(parsedData[4]));
            p.setValue2(Double.valueOf(parsedData[5]));
            p.setValue3(Double.valueOf(parsedData[6]));
            p.setValue4(Double.valueOf(parsedData[7]));
            p.setValue5(Double.valueOf(parsedData[8]));
            p.setValue6(Double.valueOf(parsedData[9]));
            p.setValue7(Double.valueOf(parsedData[10]));
            p.setValue8(Double.valueOf(parsedData[11]));
            p.setValue9(Double.valueOf(parsedData[12]));
            p.setValue10(Double.valueOf(parsedData[13]));
            p.setPupils(Integer.valueOf(parsedData[14]));
            p.setDat(dat);
            s.save(p);

            //}
        }

        // System.out.println(data);
        fis.close();

        //csv
        /*
          fileWriter.close();
          cw.close();
          */
    } catch (IOException ex) {
        Logger.getLogger(App.class.getName()).log(Level.SEVERE, null, ex);
    }

}

From source file:org.codehaus.groovy.grails.web.util.StreamByteBuffer.java

public String readAsString(Charset charset) throws CharacterCodingException {
    int unreadSize = totalBytesUnread();
    if (unreadSize > 0) {
        CharsetDecoder decoder = charset.newDecoder().onMalformedInput(CodingErrorAction.REPLACE)
                .onUnmappableCharacter(CodingErrorAction.REPLACE);
        CharBuffer charbuffer = CharBuffer.allocate(unreadSize);
        ByteBuffer buf = null;/* ww w .  j a v a2 s . c om*/
        while (prepareRead() != -1) {
            buf = currentReadChunk.readToNioBuffer();
            boolean endOfInput = (prepareRead() == -1);
            CoderResult result = decoder.decode(buf, charbuffer, endOfInput);
            if (endOfInput) {
                if (!result.isUnderflow()) {
                    result.throwException();
                }
            }
        }
        CoderResult result = decoder.flush(charbuffer);
        if (buf.hasRemaining()) {
            throw new IllegalStateException("There's a bug here, buffer wasn't read fully.");
        }
        if (!result.isUnderflow()) {
            result.throwException();
        }
        charbuffer.flip();
        String str;
        if (charbuffer.hasArray()) {
            int len = charbuffer.remaining();
            char[] ch = charbuffer.array();
            if (len != ch.length) {
                ch = ArrayUtils.subarray(ch, 0, len);
            }
            str = StringCharArrayAccessor.createString(ch);
        } else {
            str = charbuffer.toString();
        }
        return str;
    }
    return null;
}