Example usage for org.apache.commons.io.input CharSequenceInputStream CharSequenceInputStream

List of usage examples for org.apache.commons.io.input CharSequenceInputStream CharSequenceInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.input CharSequenceInputStream CharSequenceInputStream.

Prototype

public CharSequenceInputStream(final CharSequence cs, final String charset) 

Source Link

Document

Constructor, calls #CharSequenceInputStream(CharSequence,String,int) with a buffer size of 2048.

Usage

From source file:com.smartsheet.api.internal.util.StreamUtilTest.java

@Test
public void testReadBytesFromStream() throws Exception {
    final String testString = "fuzzy wuzzy was a bear; fuzzy wuzzy had no hair...";
    final byte[] testBytes = testString.getBytes("UTF-8");
    final InputStream inputStream = new CharSequenceInputStream(testString, "UTF-8");
    final ByteArrayOutputStream copyStream = new ByteArrayOutputStream();

    // this takes what was in inputStream, copies it into copyStream, and either resets inputStream (if supported)
    // or returns a new stream around the bytes read
    final InputStream backupStream = StreamUtil.cloneContent(inputStream, StreamUtil.ONE_MB, copyStream);
    if (backupStream == inputStream) {
        System.out.println("same stream returned (reset)");
        // verify readBytesFromStream gets everything from the inputStream (it also verifies cloneContent resets the source)
        byte[] streamBytes = StreamUtil.readBytesFromStream(inputStream);
        Assert.assertArrayEquals(testBytes, streamBytes); // it's all US-ASCII so it should match UTF-8 bytes
    } else {//from   w  ww .j  a  va2s . c  o m
        System.out.println("new stream returned");
        byte[] backupBytes = StreamUtil.readBytesFromStream(backupStream);
        Assert.assertArrayEquals(testBytes, backupBytes);
    }

    Assert.assertArrayEquals(testBytes, copyStream.toByteArray());
}

From source file:com.tupilabs.pbs.parser.NodeXmlParser.java

@Override
public List<Node> parse(String xml) throws ParseException {
    try {//from  w  ww. j av  a 2 s .  co m
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final SAXParser saxParser = factory.newSAXParser();
        final NodeXmlHandler handler = new NodeXmlHandler();

        saxParser.parse(new CharSequenceInputStream(xml, Charset.defaultCharset()), handler);

        return handler.getNodes();
    } catch (IOException ioe) {
        throw new ParseException(ioe);
    } catch (SAXException e) {
        throw new ParseException(e);
    } catch (ParserConfigurationException e) {
        throw new ParseException(e);
    }
}

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

@Issue("JENKINS-21670")
@Test/*from w  w  w.j a v a  2  s  . c  o m*/
public void shouldModifyStream() throws IOException {
    final int nrLines = FilteredConstants.DEFAULT_DECODER_CAPACITY;
    String inputContents = IntStream.range(0, nrLines).mapToObj(i -> "Line " + i)
            .collect(joining(System.lineSeparator()));
    CharSequenceInputStream input = new CharSequenceInputStream(inputContents, UTF_8);
    ContentFilter filter = s -> s.replace("Line", "Network");
    FilteredOutputStream output = new FilteredOutputStream(testOutput, filter);

    IOUtils.copy(input, output);
    output.flush();
    String outputContents = new String(testOutput.toByteArray(), UTF_8);

    assertThat(outputContents).isNotEmpty();
    String[] lines = FilteredConstants.EOL.split(outputContents);
    assertThat(lines).allMatch(line -> !line.contains("Line") && line.startsWith("Network")).hasSize(nrLines);
}

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

@Issue("JENKINS-21670")
@Test//from w ww  .j  av a 2  s .c om
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:com.meltmedia.cadmium.servlets.ErrorPageFilterSelectionTest.java

/**
 * Mock up the content service for the error pages and create the filter.
 * //w w  w .j  a  va 2 s  .  c o m
 * @throws ServletException if there is a problem initializing the filter.
 * @throws IOException if there is a problem mocking the content service.
 */
@Before
public void beforeTest() throws IOException, ServletException {
    ContentService contentService = mock(ContentService.class);
    when(contentService.getResourceAsStream(startsWith("/hcp"))).thenReturn(null);
    when(contentService.getResourceAsStream(startsWith("/patient/blah"))).thenReturn(null);
    when(contentService.getResourceAsStream("/404.html"))
            .thenReturn(new CharSequenceInputStream("404", "UTF-8"));
    when(contentService.getResourceAsStream("/patient/404.html"))
            .thenReturn(new CharSequenceInputStream("patient/404", "UTF-8"));
    when(contentService.getResourceAsStream("/patient/4xx.html"))
            .thenReturn(new CharSequenceInputStream("patient/4xx", "UTF-8"));
    when(contentService.getResourceAsStream("/407.html")).thenReturn(null);
    when(contentService.getResourceAsStream("/412.html")).thenReturn(null);
    when(contentService.getResourceAsStream("/40x.html"))
            .thenReturn(new CharSequenceInputStream("40x", "UTF-8"));
    when(contentService.getResourceAsStream("/41x.html")).thenReturn(null);
    when(contentService.getResourceAsStream("/4xx.html"))
            .thenReturn(new CharSequenceInputStream("4xx", "UTF-8"));
    when(contentService.getResourceAsStream("/501.html"))
            .thenReturn(new CharSequenceInputStream("501", "UTF-8"));
    when(contentService.getResourceAsStream("/502.html")).thenReturn(null);
    when(contentService.getResourceAsStream("/510.html")).thenReturn(null);
    when(contentService.getResourceAsStream("/50x.html"))
            .thenReturn(new CharSequenceInputStream("50x", "UTF-8"));
    when(contentService.getResourceAsStream("/51x.html")).thenReturn(null);
    when(contentService.getResourceAsStream("/5xx.html"))
            .thenReturn(new CharSequenceInputStream("5xx", "UTF-8"));

    filter = new ErrorPageFilter();
    filter.setContentService(contentService);

    filter.init(mock(FilterConfig.class));

}

From source file:org.biouno.drmaa_pbs.parser.NodeXmlParser.java

public List<Node> parse(String xml) throws ParseException {
    try {//from   w w  w  . j av  a  2 s  .  com
        final SAXParserFactory factory = SAXParserFactory.newInstance();
        final SAXParser saxParser = factory.newSAXParser();
        final NodeXmlHandler handler = new NodeXmlHandler();

        saxParser.parse(new CharSequenceInputStream(xml, Charset.defaultCharset()), handler);

        return handler.getNodes();
    } catch (IOException ioe) {
        throw new ParseException(ioe);
    } catch (SAXException e) {
        throw new ParseException(e);
    } catch (ParserConfigurationException e) {
        throw new ParseException(e);
    }
}

From source file:org.opennms.netmgt.integrations.R.RScriptExecutor.java

/**
 * Executes by given script by://from www  .  j  av a 2 s  .c  o m
 *   - Searching both the classpath and the filesystem for the path
 *   - Copying the script at the given path to a temporary file and
 *     performing variable substitution with the arguments using Freemarker.
 *   - Invoking the script with commons-exec
 *   - Converting the input table to CSV and passing this to the process via stdin
 *   - Parsing stdout, expecting CSV output, and converting this to an immutable table
 */
public RScriptOutput exec(String script, RScriptInput input) throws RScriptException {
    Preconditions.checkNotNull(script, "script argument");
    Preconditions.checkNotNull(input, "input argument");

    // Grab the script/template
    Template template;
    try {
        template = m_freemarkerConfiguration.getTemplate(script);
    } catch (IOException e) {
        throw new RScriptException("Failed to read the script.", e);
    }

    // Create a temporary file
    File scriptOnDisk;
    try {
        scriptOnDisk = File.createTempFile("Rcsript", "R");
        scriptOnDisk.deleteOnExit();
    } catch (IOException e) {
        throw new RScriptException("Failed to create a temporary file.", e);
    }

    // Perform variable substitution and write the results to the temporary file
    try (FileOutputStream fos = new FileOutputStream(scriptOnDisk); Writer out = new OutputStreamWriter(fos);) {
        template.process(input.getArguments(), out);
    } catch (IOException | TemplateException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to process the template.", e);
    }

    // Convert the input matrix to a CSV string which will be passed to the script via stdin.
    // The table may be large, so we try and avoid writing it to disk
    StringBuilder inputTableAsCsv;
    try {
        inputTableAsCsv = toCsv(input.getTable());
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("Failed to convert the input table to CSV.", e);
    }

    // Invoke Rscript against the script (located in a temporary file)
    CommandLine cmdLine = new CommandLine(RSCRIPT_BINARY);
    cmdLine.addArgument(scriptOnDisk.getAbsolutePath());

    // Use commons-exec to execute the process
    DefaultExecutor executor = new DefaultExecutor();

    // Use the CharSequenceInputStream in order to avoid explicitly converting
    // the StringBuilder a string and then an array of bytes.
    InputStream stdin = new CharSequenceInputStream(inputTableAsCsv, Charset.forName("UTF-8"));
    ByteArrayOutputStream stderr = new ByteArrayOutputStream();
    ByteArrayOutputStream stdout = new ByteArrayOutputStream();
    executor.setStreamHandler(new PumpStreamHandler(stdout, stderr, stdin));

    // Fail if we get a non-zero exit code
    executor.setExitValue(0);

    // Fail if the process takes too long
    ExecuteWatchdog watchdog = new ExecuteWatchdog(SCRIPT_TIMEOUT_MS);
    executor.setWatchdog(watchdog);

    // Execute
    try {
        executor.execute(cmdLine);
    } catch (IOException e) {
        scriptOnDisk.delete();
        throw new RScriptException("An error occured while executing Rscript, or the requested script.",
                inputTableAsCsv.toString(), stderr.toString(), stdout.toString(), e);
    }

    // Parse and return the results
    try {
        ImmutableTable<Long, String, Double> table = fromCsv(stdout.toString());
        return new RScriptOutput(table);
    } catch (Throwable t) {
        throw new RScriptException("Failed to parse the script's output.", inputTableAsCsv.toString(),
                stderr.toString(), stdout.toString(), t);
    } finally {
        scriptOnDisk.delete();
    }
}