Example usage for java.io Reader read

List of usage examples for java.io Reader read

Introduction

In this page you can find the example usage for java.io Reader read.

Prototype

public int read(char cbuf[]) throws IOException 

Source Link

Document

Reads characters into an array.

Usage

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  . j a  v a  2 s  .  c  o  m*/
    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:net.sf.jasperreports.engine.JRResultSetDataSource.java

protected String clobToString(Clob clob) throws JRException {
    try {// www.ja  v a  2  s  . c om
        int bufSize = 8192;
        char[] buf = new char[bufSize];

        Reader reader = new BufferedReader(clob.getCharacterStream(), bufSize);
        StringBuilder str = new StringBuilder((int) clob.length());

        for (int read = reader.read(buf); read > 0; read = reader.read(buf)) {
            str.append(buf, 0, read);
        }

        return str.toString();
    } catch (SQLException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_CLOB_VALUE_READ_FAILURE, null, e);
    } catch (IOException e) {
        throw new JRException(EXCEPTION_MESSAGE_KEY_RESULT_SET_CLOB_VALUE_READ_FAILURE, null, e);
    }
}

From source file:JavaViewer.java

void open(String name) {
    final String textString;

    if ((name == null) || (name.length() == 0))
        return;//from w  w w .j a  v a 2 s. c  o  m

    File file = new File(name);
    if (!file.exists()) {
        String message = "Err file no exist";
        displayError(message);
        return;
    }

    try {
        FileInputStream stream = new FileInputStream(file.getPath());
        try {
            Reader in = new BufferedReader(new InputStreamReader(stream));
            char[] readBuffer = new char[2048];
            StringBuffer buffer = new StringBuffer((int) file.length());
            int n;
            while ((n = in.read(readBuffer)) > 0) {
                buffer.append(readBuffer, 0, n);
            }
            textString = buffer.toString();
            stream.close();
        } catch (IOException e) {
            // Err_file_io
            String message = "Err_file_io";
            displayError(message);
            return;
        }
    } catch (FileNotFoundException e) {
        String message = "Err_not_found";
        displayError(message);
        return;
    }
    // Guard against superfluous mouse move events -- defer action until
    // later
    Display display = text.getDisplay();
    display.asyncExec(new Runnable() {
        public void run() {
            text.setText(textString);
        }
    });

    // parse the block comments up front since block comments can go across
    // lines - inefficient way of doing this
    lineStyler.parseBlockComments(textString);
}

From source file:com.xebialabs.overthere.cifs.winrm.WinRmClient.java

/**
 * Handle the httpResponse and return the SOAP XML String.
 *///from   w  w  w .  ja  v a 2 s. com
protected String handleResponse(final HttpResponse response, final HttpContext context) throws IOException {
    final HttpEntity entity = response.getEntity();
    if (null == entity.getContentType()
            || !entity.getContentType().getValue().startsWith("application/soap+xml")) {
        throw new WinRmRuntimeIOException("Error when sending request to " + targetURL
                + "; Unexpected content-type: " + entity.getContentType());
    }

    final InputStream is = entity.getContent();
    final Writer writer = new StringWriter();
    final Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
    try {
        int n;
        final char[] buffer = new char[1024];
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } finally {
        closeQuietly(reader);
        closeQuietly(is);
        consume(response.getEntity());
    }

    return writer.toString();
}

From source file:io.sqp.client.impl.SqpConnectionImpl.java

CompletableFuture<Void> send(Reader reader) {
    int bufSize = Math.min(MAX_MSG_BUFFER_SIZE, _session.getMaxTextMessageBufferSize());
    return CompletableFuture.runAsync(() -> {
        char[] buffer = new char[bufSize];
        int bytesRead;
        try (Writer output = _endpoint.getSendWriter()) {
            while ((bytesRead = reader.read(buffer)) > 0) {
                output.write(buffer, 0, bytesRead);
            }//from   www.  j  av a 2s.  c  om
        } catch (IOException e) {
            throw new CompletionException(new SqpIOException(e));
        }
    }, _sendingService).exceptionally(new FailHandler(this));
}

From source file:nl.sogeti.android.gpstracker.actions.ShareTrack.java

public String convertStreamToString(InputStream is) throws IOException {
    /*//from www .j  a  v a  2s  .c  o m
     * To convert the InputStream to String we use the Reader.read(char[] buffer) method. We iterate until the Reader return -1 which means there's no more data to read. We use the StringWriter
     * class to produce the string.
     */
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {
        return "";
    }
}

From source file:org.zilverline.extractors.AbstractExtractor.java

/**
 * This method extracts all relevant info of the file as an ParsedFileInfo object. Uses getContent as callback.
 * /*from w  w  w.j av  a  2  s  . c  om*/
 * @param f the File to extract content from
 * 
 * @return ParsedFileInfo the object containing relevant info of the provided file
 */
public final ParsedFileInfo extractInfo(final File f) {
    if (f == null) {
        log.warn("Something went terribly wrong, file = null, returning null ");
        return null;
    }
    try {
        setFile(f);

        Reader reader = getContent(f);
        fileInfo.setReader(reader);
        // get the summary from the reader
        if (reader != null) {
            String summary = fileInfo.getSummary();

            if (!StringUtils.hasText(summary)) {
                char[] sumChars = new char[SUMMARY_SIZE];
                int numChars = 0;
                try {
                    if (reader.markSupported()) {
                        reader.mark(SUMMARY_SIZE);
                        numChars = reader.read(sumChars);
                        reader.reset();
                    }
                    if (numChars > 0) {
                        summary = new String(sumChars, 0, numChars);
                    }
                    if (log.isDebugEnabled()) {
                        log.debug("Summary extracted from reader: " + summary);
                    }
                    setSummary(getSummaryFromContent(summary));
                } catch (IOException e) {
                    log.warn("Error extracting summary form reader", e);
                }
            }
        }
        // Set the title if there's none yet
        if (!StringUtils.hasLength(fileInfo.getTitle())) {
            fileInfo.setTitle(FileUtils.getBasename(f));
        }
    } catch (Exception e) {
        // here we don't throw any, since we do not want to interrupt the indexing process
        log.warn("Unexpected Error extracting content from  " + f.getName(), e);
    } catch (OutOfMemoryError e) {
        // this happens with very, very large Documents
        log.error("Very Serious Error. Out of Memory for very large documents: " + f.getName()
                + ", try increasing your JVM heap  size: for example, start your server with option '-Xmx128m'."
                + " Skipping file.", e);
    } catch (Throwable e) {
        log.error("Very Serious Error while extracting contents from: " + f.getName(), e);
    }

    return fileInfo;
}

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 ww  . j  a  va2s. com

            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:org.syncope.core.workflow.ActivitiUserWorkflowAdapter.java

@Override
public WorkflowDefinitionTO getDefinition() throws WorkflowException {

    ProcessDefinition procDef;//from  ww  w  .  jav a2  s  . c o  m
    try {
        procDef = repositoryService.createProcessDefinitionQuery()
                .processDefinitionKey(ActivitiUserWorkflowAdapter.WF_PROCESS_ID).latestVersion().singleResult();
    } catch (ActivitiException e) {
        throw new WorkflowException(e);
    }

    InputStream procDefIS = repositoryService.getResourceAsStream(procDef.getDeploymentId(),
            WF_PROCESS_RESOURCE);
    Reader reader = null;
    Writer writer = new StringWriter();
    try {
        reader = new BufferedReader(new InputStreamReader(procDefIS));

        int n;
        char[] buffer = new char[1024];
        while ((n = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, n);
        }
    } catch (IOException e) {
        LOG.error("While reading workflow definition {}", procDef.getKey(), e);
    } finally {
        try {
            if (reader != null) {
                reader.close();
            }
            if (procDefIS != null) {
                procDefIS.close();
            }
        } catch (IOException ioe) {
            LOG.error("While closing input stream for {}", procDef.getKey(), ioe);
        }
    }

    WorkflowDefinitionTO definitionTO = new WorkflowDefinitionTO();
    definitionTO.setId(ActivitiUserWorkflowAdapter.WF_PROCESS_ID);
    definitionTO.setXmlDefinition(writer.toString());

    return definitionTO;
}