Example usage for org.apache.commons.io.output WriterOutputStream WriterOutputStream

List of usage examples for org.apache.commons.io.output WriterOutputStream WriterOutputStream

Introduction

In this page you can find the example usage for org.apache.commons.io.output WriterOutputStream WriterOutputStream.

Prototype

public WriterOutputStream(Writer writer, String charsetName) 

Source Link

Document

Constructs a new WriterOutputStream with a default output buffer size of 1024 characters.

Usage

From source file:fi.jumi.core.stdout.OutputCapturer.java

public OutputCapturer(OutputStream realOut, OutputStream realErr, Charset charset) {
    OutputStream capturedOut = new WriterOutputStream(outCapturer, charset);
    OutputStream capturedErr = new WriterOutputStream(errCapturer, charset);
    err = createNonSynchronizedPrintStream(new OutputStreamReplicator(realErr, capturedErr), charset);
    out = SynchronizedPrintStream.create(new OutputStreamReplicator(realOut, capturedOut), charset, err);
}

From source file:name.martingeisse.ecobuild.util.ToolhostCommandInvocation.java

@Override
protected void invoke(List<String> tokenList) throws IOException {
    try {//from ww w. ja v  a2 s  .  com

        final MyLoggerWriter loggerWriter = new MyLoggerWriter(getLogger());
        final OutputStream loggerOutputStream = new WriterOutputStream(loggerWriter, "ascii");
        IFilePointer stdin = new EmptyFilePointer();
        IFilePointer stdout = new StreamFilePointer(loggerOutputStream);
        IFilePointer stderr = stdout;

        String[] tokens = tokenList.toArray(new String[tokenList.size()]);
        ToolhostProcessSet processSet = new ToolhostProcessSet(new ToolhostFileSystem());
        ToolhostProcess process = processSet.createInitialProcess(getWorkingDirectory(), stdin, stdout, stderr);
        stdin.releaseReference();
        stdout.releaseReference();
        process.exec(tokens[0], tokens);
        processSet.run();
        loggerOutputStream.flush();
        loggerWriter.endStartedLine();

    } catch (Exception e) {
        throw new IOException(e);
    }
}

From source file:ee.ria.xroad.common.util.PasswordStore.java

private static char[] byteToChar(byte[] bytes) throws IOException {
    if (bytes == null) {
        return null;
    }/*from  w  ww .j a v  a  2 s .  com*/

    CharArrayWriter writer = new CharArrayWriter(bytes.length);
    WriterOutputStream os = new WriterOutputStream(writer, UTF_8);
    os.write(bytes);
    os.close();

    return writer.toCharArray();
}

From source file:com.ppcxy.cyfm.showcase.demos.utilities.io.IODemo.java

@Test
public void workWithStream() {
    InputStream in = null;//from ww w  .  j av  a2s. c  o m
    try {
        String content = "Stream testing";

        // String - > InputStream.
        in = IOUtils.toInputStream(content, "UTF-8");

        // String - > OutputStream
        System.out.println("String to OutputStram:");
        IOUtils.write(content, System.out, "UTF-8");

        // //////////////////
        // InputStream/Reader -> String
        System.out.println("\nInputStram to String:");
        System.out.println(IOUtils.toString(in, "UTF-8"));

        // InputStream/Reader -> OutputStream/Writer ???.
        InputStream in2 = IOUtils.toInputStream(content); // ?inputSteam
        System.out.println("InputStream to OutputStream:");
        IOUtils.copy(in2, System.out);

        // /////////////////
        // InputStream ->Reader
        InputStreamReader reader = new InputStreamReader(in, Charsets.UTF_8);
        // Reader->InputStream
        ReaderInputStream in3 = new ReaderInputStream(reader, Charsets.UTF_8);

        // OutputStream ->Writer
        OutputStreamWriter writer = new OutputStreamWriter(System.out, Charsets.UTF_8);
        // Writer->OutputStream
        WriterOutputStream out2 = new WriterOutputStream(writer, Charsets.UTF_8);

        // ////////////////////
        // WriterString.
        StringWriter sw = new StringWriter();
        sw.write("I am String writer");
        System.out.println("\nCollect writer content:");
        System.out.println(sw.toString());

    } catch (IOException e) {
        Exceptions.unchecked(e);
    } finally {
        // ?Stream
        IOUtils.closeQuietly(in);
    }
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.AmazonHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);// www. ja v a 2  s .co  m
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured kindlegen executable
        logger.info("Kindlegen will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Kindlegen will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());
    cmdLine.addArgument("-c0");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter stdoutWriter = new StringWriter();
    StringWriter stderrWriter = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(stdoutWriter, Charset.forName("UTF-8"));
    WriterOutputStream writerErrorStream = new WriterOutputStream(stderrWriter, Charset.forName("UTF-8"));

    ExecuteStreamHandler kindlegenStreamHandler = new PumpStreamHandler(writerOutputStream, writerErrorStream);
    executor.setStreamHandler(kindlegenStreamHandler);

    logger.debug("Launching kindlegen:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Kindlegen failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Kindlegen execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"kindlegen\"")) {
                logger.error("Kindlegen could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("Kindlegen's execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    try {
        String stderrOutput = stderrWriter.getBuffer().toString();
        stderrWriter.close();
        if (stderrOutput.isEmpty() == false) {
            logger.error("Kindlegen logged some errors:");
            logger.error(stderrOutput);
        }
    } catch (IOException e) {
        logger.error("Error closing kindlegen's stderr buffer");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += stdoutWriter.getBuffer().toString();
        stdoutWriter.close();

    } catch (IOException e) {
        logger.error("Error closing kindlegen's stdout buffer:");
        logger.error(e.getMessage(), e);
    }

    logger.debug("Kindlegen output: \n" + output);

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    logger.debug("Moving Kindlegen output file: " + mobiFilename);

    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);
    return tempMobiFilepath.toFile();
}

From source file:com.bigdata.rdf.properties.xml.PropertiesXMLWriter.java

/**
 * Creates a new {@link PropertiesXMLWriter} that will write to the supplied
 * {@link Writer}./*from   ww  w  .j a  va2  s  .  c  o  m*/
 * 
 * @param writer
 *            The {@link Writer} to write the {@link Properties} document
 *            to.
 */
public PropertiesXMLWriter(final Writer writer) {

    this.os = new WriterOutputStream(writer, PropertiesFormat.XML.getCharset());

}

From source file:com.bigdata.rdf.properties.text.PropertiesTextWriter.java

/**
 * Creates a new {@link PropertiesTextWriter} that will write to the supplied
 * {@link Writer}./*from  w ww  .  ja  v a2  s.c  om*/
 * 
 * @param writer
 *            The {@link Writer} to write the {@link Properties} document
 *            to.
 */
public PropertiesTextWriter(final Writer writer) {

    this.os = new WriterOutputStream(writer, PropertiesFormat.TEXT.getCharset());

}

From source file:net.sf.vntconverter.VntConverter.java

/**
 * Dekodiert einen UTF-8-QUOTED-PRINTABLE-String in einen Java-Unicode-String.
 *//*from   w  w  w  .j  a  v a2  s. c  o m*/
public String decode(String in) {
    try {
        InputStream input = MimeUtility.decode(new ReaderInputStream(new StringReader(in), "UTF-8"),
                "quoted-printable");
        StringWriter sw = new StringWriter();
        OutputStream output = new WriterOutputStream(sw, "UTF-8");
        copyAndClose(input, output);
        return sw.toString();
    } catch (Exception e) {
        throw new RuntimeException("Exception caught in VntConverter.encode(in):", e);
    }

}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.latex2html.PandocLatexToHtmlConverter.java

@Override
public Document convert(File tex, String title) {
    logger.debug("Start convert() with file " + tex.toPath().toAbsolutePath().toString() + ", title: " + title);

    CommandLine cmdLine;//  w  w  w  .  j av  a  2  s  . c om
    if (execPath != null) {
        // Run the configured pandoc executable
        logger.info("Pandoc will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Pandoc will be run within the PATH variable.");
        cmdLine = new CommandLine("pandoc");
    }

    cmdLine.addArgument("--from=latex");
    cmdLine.addArgument("--to=html5");
    cmdLine.addArgument("--asciimathml"); // With this option, pandoc does not render latex formulas

    cmdLine.addArgument("${file}");

    HashMap<String, Path> map = new HashMap<String, Path>();
    map.put("file", Paths.get(tex.toURI()));

    cmdLine.setSubstitutionMap(map);

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000); // max execution time 1 minute
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler pandocStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(pandocStreamHandler);

    logger.debug("Launching pandoc:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("Pandoc's execution failed, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("Pandoc execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();

            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"pandoc\"")) {
                logger.error("Pandoc could not be found! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("pandoc conversion thread got interrupted, exiting...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // add html document structure to output
    // pandoc returns no document markup (html, head, body)
    // therefore we have to use a template
    String htmlOutput = "<!DOCTYPE html>\n" + "<html>\n" + "<head>\n" +
    // set title
            "<title>" + title + "</title>\n" +
            // include css
            "<link rel=\"stylesheet\" type=\"text/css\" href=\"main.css\"></link>\n" + "</head>\n" + "<body>";
    try {
        htmlOutput += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading html result from StringBuffer...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }

    // Close tags in template
    htmlOutput += "</body>\n" + "</html>";

    // output loading as JDOM Document
    SAXBuilder sax = new SAXBuilder();
    Document document = null;
    try {
        document = sax.build(new StringReader(htmlOutput));
    } catch (JDOMException e) {
        logger.error("JDOM Parsing error");
        logger.error(e.getMessage(), e);
        System.exit(1);
    } catch (IOException e) {
        logger.error("Error reading from String...");
        logger.error(e.getMessage(), e);
        System.exit(1);
    }
    return document;
}

From source file:at.ac.tuwien.ims.latex2mobiformulaconv.converter.html2mobi.CalibreHtmlToMobiConverter.java

@Override
public File convertToMobi(File htmlFile) {
    logger.debug("Enter convertToMobi()...");

    if (htmlFile == null) {
        logger.error("Document is null, aborting...");
        System.exit(1);/*from www  . j  a va 2s .  com*/
    }

    CommandLine cmdLine;
    if (execPath != null) {
        // Run the configured calibre ebook-convert executable
        logger.info("Calibre ebook-convert will be run from: " + execPath.toString());
        cmdLine = new CommandLine(execPath.toFile());
    } else {
        // Run in system PATH environment
        logger.info("Calibre ebook-convert will be run within the PATH variable.");
        cmdLine = new CommandLine(command);
    }

    // cli command: ebook-convert input_file.html output_file.mobi --mobi-file-type=new

    // Run configuration
    cmdLine.addArgument(Paths.get(htmlFile.toURI()).toAbsolutePath().toString());

    String mobiFilename = htmlFile.getName().toString().replace(".html", ".mobi").toString();
    Path tempMobiFilepath = Paths.get(htmlFile.toURI()).getParent().resolve(mobiFilename);

    logger.debug("Mobi output file: " + tempMobiFilepath.toAbsolutePath().toString());
    cmdLine.addArgument(tempMobiFilepath.toAbsolutePath().toString());

    // Output will be in format "KF8" only, old format does not allow external CSS files
    cmdLine.addArgument("--mobi-file-type=new");

    DefaultExecuteResultHandler resultHandler = new DefaultExecuteResultHandler();

    ExecuteWatchdog watchdog = new ExecuteWatchdog(60 * 1000);
    Executor executor = new DefaultExecutor();
    executor.setExitValue(1);
    executor.setWatchdog(watchdog);
    StringWriter writer = new StringWriter();
    WriterOutputStream writerOutputStream = new WriterOutputStream(writer, Charset.forName("UTF-8"));

    ExecuteStreamHandler calibreStreamHandler = new PumpStreamHandler(writerOutputStream, System.err);
    executor.setStreamHandler(calibreStreamHandler);

    logger.debug("Launching calibres ebook-convert:");
    logger.debug(cmdLine.toString());

    try {
        executor.execute(cmdLine, resultHandler);
    } catch (IOException e) {
        logger.error("calibres ebook-convert failed to execute:");
        logger.error(e.getMessage(), e);
        System.exit(-1);
    }

    try {
        resultHandler.waitFor();
        int exitValue = resultHandler.getExitValue();

        logger.debug("calibre ebook-converts execution's exit value: " + exitValue);
        ExecuteException executeException = resultHandler.getException();
        if (executeException != null && executeException.getCause() != null) {

            String exceptionKlass = executeException.getCause().getClass().getCanonicalName();
            String exceptionMessage = executeException.getCause().getMessage();
            if (exceptionKlass.endsWith("IOException")
                    || exceptionMessage.contains("Cannot run program \"ebook-convert\"")) {
                logger.error("calibres ebook-convert could not be run! Exiting...");
                logger.debug(executeException);
                System.exit(1);
            }
            logger.debug(exceptionKlass + ": " + exceptionMessage);
        }

    } catch (InterruptedException e) {
        logger.error("calibre ebook-converts execution got interrupted: ");
        logger.error(e.getMessage(), e);
    }

    String output = "";
    try {
        output += writer.getBuffer().toString();
        writer.close();

    } catch (IOException e) {
        logger.error("Error reading calibre ebook-converts output from buffer:");
        logger.error(e.getMessage(), e);

    }

    logger.debug("Calibre ebook-convert output: \n" + output);

    return tempMobiFilepath.toFile();
}