Example usage for java.nio CharBuffer wrap

List of usage examples for java.nio CharBuffer wrap

Introduction

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

Prototype

public static CharBuffer wrap(CharSequence chseq, int start, int end) 

Source Link

Document

Creates a new char buffer by wrapping the given char sequence.

Usage

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.wrap("java2s.com", 0, 2);
    System.out.println(cb1.toString());

}

From source file:Main.java

public static void main(String[] args) {
    CharBuffer cb1 = CharBuffer.wrap(new char[] { 'j', 'a', 'v', 'a', '2', 's', }, 0, 2);
    System.out.println(cb1.toString());

}

From source file:MainClass.java

public static void main(String[] argv) throws Exception {
    char[] chars = new char[60];

    CharBuffer cb = CharBuffer.wrap(chars, 12, 42);

    println(cb);/*from   w  w  w. j  a  va 2  s . c  o  m*/

    cb.put("This is a test String");

    cb.flip();

    println(cb);

    cb.clear();

    cb.put("Foobar");

    println(cb);

    for (int i = 0; i < 20; i++) {
        System.out.println("[" + i + "] = " + chars[i]);
    }
}

From source file:sonia.maven.native2utf8.Native2UTF8.java

/**
 * Method description//w  w  w . j a va 2  s . c  o  m
 *
 *
 * @param src
 * @param dst
 * @param encoding
 *
 * @throws IOException
 */
public static void nativeToUTF8(File src, File dst, String encoding) throws IOException {
    BufferedReader input = null;
    BufferedWriter output = null;

    try {
        input = new BufferedReader(new InputStreamReader(new FileInputStream(src), encoding));
        output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "UTF8"));

        char[] buffer = new char[65536];
        int len;

        while ((len = input.read(buffer)) != -1) {
            if (len > 0) {
                output.write(StringEscapeUtils.unescapeJava((CharBuffer.wrap(buffer, 0, len)).toString()));
            }
        }
    } finally {
        Closeables.close(input, true);
        Closeables.close(output, true);
    }
}

From source file:org.apache.mahout.utils.nlp.collocations.llr.BloomTokenFilter.java

@Override
public boolean incrementToken() throws IOException {
    while (input.incrementToken()) {
        ByteBuffer bytes = encoder.encode(CharBuffer.wrap(termAtt.buffer(), 0, termAtt.length()));
        key.set(bytes.array(), 1.0f);//from  w  w  w. java2s  .  co  m
        boolean member = filter.membershipTest(key);
        if ((keepMembers && member) || (!keepMembers && !member)) {
            return true;
        }
    }
    return false;
}

From source file:com.cheesmo.nzb.client.NNTPConnection.java

public boolean downloadSegment(String group, String string, String downloadName) {
    try {/*w  ww. j  a v a  2  s  .co m*/
        tryConnect();
        client.selectNewsgroup(group);
        Reader reader = client.retrieveArticleBody(string);

        if (reader != null) {
            FileOutputStream fos = new FileOutputStream(
                    config.getCacheDir() + java.io.File.separator + downloadName);
            char[] buffer = new char[512];
            int charsRead = reader.read(buffer);
            while (charsRead > -1 && client.isConnected()) {
                fos.write(Charset.forName("ISO-8859-1").encode(CharBuffer.wrap(buffer, 0, charsRead)).array());
                charsRead = reader.read(buffer);
            }

            if (!client.isConnected()) {
                System.out.println("Client disconnected.");
            }
            reader.close();
            fos.flush();
            fos.close();
            return true;
        } else {
            //System.out.println("Problem retrieving " + string);
        }

    } catch (SocketException e) {
        System.out.println("Client disconnected.");
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return false;
}

From source file:org.codehaus.mojo.native2ascii.Native2Ascii.java

/**
 * Converts given file into file unicode escaped ASCII file.
 *
 * @param src/*from  w w  w.jav  a2  s. c o m*/
 * @param dst
 * @param encoding
 * @throws IOException
 */
public void nativeToAscii(final File src, final File dst, final String encoding) throws IOException {
    log.info("Converting: '" + src + "' to: '" + dst + "'");
    BufferedReader input = null;
    BufferedWriter output = null;
    try {
        if (!dst.getParentFile().exists()) {
            dst.getParentFile().mkdirs();
        }
        input = new BufferedReader(new InputStreamReader(new FileInputStream(src), encoding));
        output = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(dst), "ISO-8859-1"));

        final char[] buffer = new char[4096];
        int len;
        while ((len = input.read(buffer)) != -1) {
            output.write(nativeToAscii(CharBuffer.wrap(buffer, 0, len).toString()));
        }
    } finally {
        closeQuietly(src, input);
        closeQuietly(dst, output);
    }
}

From source file:com.cloudant.tests.UnicodeTest.java

/**
 * Copies the content of an entity to an Appendable, as a sequence of chars.
 *
 * @param destination An Appendable (such as a StringBuilder, a Writer, or a PrintStream).
 * @param reader      A Reader that wraps the InputStream of the entity returned by the given
 *                    URI./*from  w  w w .j a v a  2 s.co m*/
 *                    Should be buffered.
 * @throws RuntimeException if there is an exception reading the entity
 * @throws IOException      if there is an exception writing to the destination
 */
private static void pipeEntityContentAsChars(Appendable destination, Reader reader, URI uri)
        throws IOException {
    char[] buffer = new char[1024];
    for (;;) {
        int n;
        try {
            n = reader.read(buffer);
        } catch (SocketException e) {
            // At EOF, we may get this exception:
            // java.net.SocketException: Socket is closed
            //   at com.sun.net.ssl.internal.ssl.SSLSocketImpl.checkEOF(SSLSocketImpl.java:1284)
            //   at com.sun.net.ssl.internal.ssl.AppInputStream.read(AppInputStream.java:65)
            //   at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer
            // (AbstractSessionInputBuffer.java:149)
            //   at org.apache.http.impl.io.SocketInputBuffer.fillBuffer(SocketInputBuffer
            // .java:110)
            //   at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine
            // (AbstractSessionInputBuffer.java:264)
            //   at org.apache.http.impl.io.ChunkedInputStream.getChunkSize
            // (ChunkedInputStream.java:246)
            //   at org.apache.http.impl.io.ChunkedInputStream.nextChunk(ChunkedInputStream
            // .java:204)
            //   at org.apache.http.impl.io.ChunkedInputStream.read(ChunkedInputStream.java:167)
            //   at org.apache.http.conn.EofSensorInputStream.read(EofSensorInputStream
            // .java:138)
            //   at java.io.BufferedInputStream.read1(BufferedInputStream.java:256)
            //   at java.io.BufferedInputStream.read(BufferedInputStream.java:317)
            //   at sun.nio.cs.StreamDecoder.readBytes(StreamDecoder.java:264)
            //   at sun.nio.cs.StreamDecoder.implRead(StreamDecoder.java:306)
            //   at sun.nio.cs.StreamDecoder.read(StreamDecoder.java:158)
            //   at java.io.InputStreamReader.read(InputStreamReader.java:167)
            //   at java.io.Reader.read(Reader.java:123)
            // See also http://stackoverflow
            // .com/questions/17040698/httpcomponentss-ssl-connection-results-in-socket-is
            // -closed
            break;
        } catch (IOException e) {
            throw new RuntimeException("Error reading from " + uri, e);
        }
        if (n < 0) {
            break;
        }
        destination.append(CharBuffer.wrap(buffer, 0, n));
    }
}

From source file:io.lightlink.output.JSONResponseStream.java

public void writeFromReader(Reader reader) {
    write('"');/*from ww w  .  j  av  a 2 s  .co  m*/
    char[] buffer = new char[16000];
    long count = 0;
    int n = 0;
    try {
        while (-1 != (n = reader.read(buffer))) {

            ByteBuffer bbuffer = CHARSET.encode(CharBuffer.wrap(buffer, 0, n));
            write(bbuffer.array(), bbuffer.remaining());

            count += n;
        }
        write('"');
        reader.close();
    } catch (IOException e) {
        throw new RuntimeException(e.toString(), e);
    }
}

From source file:org.inquidia.kettle.plugins.tokenreplacement.TokenReplacement.java

public synchronized boolean processRow(StepMetaInterface smi, StepDataInterface sdi) throws KettleException {
    meta = (TokenReplacementMeta) smi;/*  w w  w. java 2s.c  om*/
    data = (TokenReplacementData) sdi;

    boolean result = true;
    Object[] r = getRow(); // This also waits for a row to be finished.

    if (first && r != null) {
        first = false;

        data.inputRowMeta = getInputRowMeta();
        data.outputRowMeta = getInputRowMeta().clone();

        if (meta.getOutputType().equalsIgnoreCase("field")) {
            meta.getFields(data.outputRowMeta, getStepname(), null, null, this, repository, metaStore);

        }
        if (meta.getOutputType().equalsIgnoreCase("file") && !meta.isOutputFileNameInField()) {
            if (meta.getOutputFileName() != null) {
                String filename = meta.buildFilename(meta.getOutputFileName(), getTransMeta(), getCopy(),
                        getPartitionID(), data.splitnr);
                openNewOutputFile(filename);
            } else {
                throw new KettleException("Output file name cannot be null.");
            }
        }
    }

    if (r == null) {
        // no more input to be expected...
        closeAllOutputFiles();
        setOutputDone();
        return false;
    }

    if (meta.getOutputType().equalsIgnoreCase("file") && !meta.isOutputFileNameInField()
            && meta.getSplitEvery() > 0 && data.rowNumber % meta.getSplitEvery() == 0) {
        if (data.rowNumber > 0) {
            closeAllOutputFiles();
            data.splitnr++;
            String filename = meta.buildFilename(meta.getOutputFileName(), getTransMeta(), getCopy(),
                    getPartitionID(), data.splitnr);
            openNewOutputFile(filename);
        }
    }

    String outputFilename = "";
    if (meta.getOutputType().equalsIgnoreCase("file") && !meta.isOutputFileNameInField()) {
        outputFilename = meta.buildFilename(meta.getOutputFileName(), getTransMeta(), getCopy(),
                getPartitionID(), data.splitnr);
    } else if (meta.getOutputType().equalsIgnoreCase("file") && meta.isOutputFileNameInField()) {
        String filenameValue = data.inputRowMeta.getString(r,
                environmentSubstitute(meta.getOutputFileNameField()), "");
        if (!Const.isEmpty(filenameValue)) {
            outputFilename = filenameValue;
        } else {
            throw new KettleException("Filename cannot be empty.");
        }
    }

    //Create token resolver
    TokenResolver resolver = new TokenResolver();

    for (TokenReplacementField field : meta.getTokenReplacementFields()) {
        if (data.inputRowMeta.indexOfValue(field.getName()) >= 0) {
            String fieldValue = environmentSubstitute(data.inputRowMeta.getString(r, field.getName(), null));
            if (fieldValue == null && !BooleanUtils
                    .toBoolean(Const.getEnvironmentVariable("KETTLE_EMPTY_STRING_DIFFERS_FROM_NULL", "N"))) {
                fieldValue = Const.nullToEmpty(fieldValue);
            }
            resolver.addToken(field.getTokenName(), fieldValue);
        } else {
            throw new KettleValueException("Field " + field.getName() + " not found on input stream.");
        }
    }

    Reader reader;
    String inputFilename = "";

    if (meta.getInputType().equalsIgnoreCase("text")) {
        reader = new TokenReplacingReader(resolver, new StringReader(meta.getInputText()),
                environmentSubstitute(meta.getTokenStartString()),
                environmentSubstitute(meta.getTokenEndString()));

    } else if (meta.getInputType().equalsIgnoreCase("field")) {
        if (data.inputRowMeta.indexOfValue(meta.getInputFieldName()) >= 0) {
            String inputString = data.inputRowMeta.getString(r, meta.getInputFieldName(), "");
            reader = new TokenReplacingReader(resolver, new StringReader(inputString),
                    environmentSubstitute(meta.getTokenStartString()),
                    environmentSubstitute(meta.getTokenEndString()));

        } else {
            throw new KettleValueException(
                    "Input field " + meta.getInputFieldName() + " not found on input stream.");
        }
    } else if (meta.getInputType().equalsIgnoreCase("file")) {
        if (meta.isInputFileNameInField()) {
            if (data.inputRowMeta.indexOfValue(environmentSubstitute(meta.getInputFileNameField())) >= 0) {
                inputFilename = data.inputRowMeta.getString(r,
                        environmentSubstitute(meta.getInputFileNameField()), "");
            } else {
                throw new KettleValueException("Input filename field "
                        + environmentSubstitute(meta.getInputFileNameField()) + " not found on input stream.");
            }
        } else {
            inputFilename = environmentSubstitute(meta.getInputFileName());
        }

        if (Const.isEmpty(inputFilename)) {
            throw new KettleValueException("Input filename cannot be empty");
        }

        FileObject file = KettleVFS.getFileObject(inputFilename, getTransMeta());
        reader = new TokenReplacingReader(resolver,
                new InputStreamReader(KettleVFS.getInputStream(inputFilename, getTransMeta())),
                environmentSubstitute(meta.getTokenStartString()),
                environmentSubstitute(meta.getTokenEndString()));

        if (meta.isAddInputFileNameToResult()) {
            ResultFile resultFile = new ResultFile(ResultFile.FILE_TYPE_GENERAL,
                    KettleVFS.getFileObject(inputFilename, getTransMeta()), getTransMeta().getName(),
                    getStepname());
            resultFile.setComment(BaseMessages.getString(PKG, "TokenReplacement.AddInputResultFile"));
            addResultFile(resultFile);
        }
    } else {
        throw new KettleException("Unsupported input type " + meta.getInputType());
    }

    Writer stringWriter = null;
    OutputStream bufferedWriter = null;

    if (meta.getOutputType().equalsIgnoreCase("field")) {
        stringWriter = new StringBufferWriter(new StringBuffer(5000));
    } else if (meta.getOutputType().equalsIgnoreCase("file")) {

        if (inputFilename.equals(outputFilename)) {
            throw new KettleException("Input and output filenames must not be the same " + inputFilename);
        }

        int fileIndex = data.openFiles.indexOf(outputFilename);
        if (fileIndex < 0) {
            openNewOutputFile(outputFilename);
            fileIndex = data.openFiles.indexOf(outputFilename);
        }

        bufferedWriter = data.openBufferedWriters.get(fileIndex);

    } else {
        throw new KettleException("Unsupported output type " + meta.getOutputType());
    }

    String output = "";

    try {
        char[] cbuf = new char[5000];
        StringBuffer sb = new StringBuffer();
        int length = 0;
        while ((length = reader.read(cbuf)) > 0) {
            if (meta.getOutputType().equalsIgnoreCase("field")) {
                stringWriter.write(cbuf, 0, length);
            } else if (meta.getOutputType().equalsIgnoreCase("file")) {
                CharBuffer cBuffer = CharBuffer.wrap(cbuf, 0, length);
                ByteBuffer bBuffer = Charset.forName(meta.getOutputFileEncoding()).encode(cBuffer);
                byte[] bytes = new byte[bBuffer.limit()];
                bBuffer.get(bytes);
                bufferedWriter.write(bytes);

            } //No else.  Anything else will be thrown to a Kettle exception prior to getting here.
            cbuf = new char[5000];
        }

        if (meta.getOutputType().equalsIgnoreCase("field")) {
            output += stringWriter.toString();
        } else if (meta.getOutputType().equalsIgnoreCase("file")) {
            bufferedWriter.write(meta.getOutputFileFormatString().getBytes());
        }
    } catch (IOException ex) {
        throw new KettleException(ex.getMessage(), ex);
    } finally {
        try {
            reader.close();
            if (stringWriter != null) {
                stringWriter.close();
            }

            reader = null;
            stringWriter = null;

        } catch (IOException ex) {
            throw new KettleException(ex.getMessage(), ex);
        }

    }

    if (meta.getOutputType().equalsIgnoreCase("field")) {
        r = RowDataUtil.addValueData(r, data.outputRowMeta.size() - 1, output);
    } else if (meta.getOutputType().equalsIgnoreCase("file")) {
        incrementLinesWritten();
    }

    putRow(data.outputRowMeta, r); // in case we want it to go further...
    data.rowNumber++;
    if (checkFeedback(getLinesOutput())) {
        logBasic("linenr " + getLinesOutput());
    }

    return result;
}