Example usage for org.apache.commons.io IOUtils toInputStream

List of usage examples for org.apache.commons.io IOUtils toInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io IOUtils toInputStream.

Prototype

public static InputStream toInputStream(String input, String encoding) throws IOException 

Source Link

Document

Convert the specified string to an input stream, encoded as bytes using the specified character encoding.

Usage

From source file:com.qualogy.qafe.bind.io.document.LocalXSDResolver.java

private InputStream stringToStream(String string) {
    InputStream result = null;// w w w  .  j a  v  a 2  s .  co  m
    try {
        result = IOUtils.toInputStream(string, "UTF-8");
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }
    return result;
}

From source file:ch.entwine.weblounge.common.impl.content.file.LazyFileResourceImpl.java

/**
 * Loads the complete file.// w  ww .jav a2 s  . c om
 */
protected void loadPage() {
    try {

        // Get a hold of the file reader
        FileResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new FileResourceReader();
            // No need to keep the reference, since we're done after this
        }

        // Load the file
        file = reader.read(IOUtils.toInputStream(fileXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        isBodyLoaded = true;
        cleanupAfterLoading();
    } catch (Throwable e) {
        logger.error("Failed to lazy-load body of {}", uri);
        throw new IllegalStateException("Failed to lazy-load body of " + uri, e);
    }
}

From source file:ch.entwine.weblounge.common.impl.content.movie.LazyMovieResourceImpl.java

/**
 * Loads the complete audio visual.//www  . j a v  a  2 s . com
 */
protected void loadAudioVisual() {
    try {

        // Get a hold of the audio visual reader
        MovieResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new MovieResourceReader();
            // No need to keep the reference, since we're done after this
        }

        // Load the audio visual
        audioVisual = reader.read(IOUtils.toInputStream(audiovisualXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        isBodyLoaded = true;
        cleanupAfterLoading();
    } catch (Throwable e) {
        logger.error("Failed to lazy-load body of {}", uri);
        throw new IllegalStateException("Failed to lazy-load body of " + uri, e);
    }
}

From source file:com.github.sleroy.junit.mail.server.MailSaverTest.java

@Test
public void testSaveEmailAndNotify_no_relay() throws Exception {
    // GIVEN I have a server accurately configured (relay domains)
    MailServerModel mailServerModel = new MailServerModel();
    ServerConfiguration serverConfiguration = new ServerConfiguration();

    serverConfiguration.relayDomainsList((List) null);
    MailSaver mailSaver = new MailSaver(serverConfiguration);

    // AND I don't forget to register the mailServerModel
    mailSaver.addObserver(mailServerModel);

    // WHEN I sent a mail
    mailSaver.saveEmailAndNotify(FROM, TO, IOUtils.toInputStream("test", "UTF-8"));

    // THEN THE MAILS ARE REJECTED
    Assert.assertEquals(1, mailServerModel.getEmailModels().size());
    EmailModel emailModel = mailServerModel.getEmailModels().get(0);
    assertNotNull(emailModel);//from   w w  w  .j ava  2  s .  com

    //
}

From source file:com.twinsoft.convertigo.eclipse.editors.jscript.JscriptTreeFunctionEditor.java

public void init(IEditorSite site, IEditorInput input) throws PartInitException {
    file = ((FileEditorInput) input).getFile();
    treeObject = ((JscriptTreeFunctionEditorInput) input).getFunctionTreeObject();

    try {/*from  w w w .jav a 2 s .  c om*/
        file.setCharset("UTF-8", null);
    } catch (CoreException e1) {
        ConvertigoPlugin.logDebug("Failed to set UTF-8 charset for editor file: " + e1);
    }

    try {
        // Create a temp  file to hold data
        InputStream sbisHandlersStream = IOUtils.toInputStream(treeObject.getFunction(), "UTF-8");

        // Overrides temp file with data
        if (file.exists()) {
            try {
                file.setContents(sbisHandlersStream, true, false, null);
            } catch (CoreException e) {
                ConvertigoPlugin.logException(e, "Error while editing the function");
            }
        }
        // Create a temp file to hold data
        else {
            try {
                file.create(sbisHandlersStream, true, null);
            } catch (CoreException e) {
                ConvertigoPlugin.logException(e, "Error while editing the function");
            }
        }

        setSite(site);
        setInput(input);
        eSite = site;
        eInput = input;
        setPartName(file.getName());
    } catch (Exception e) {
        throw new PartInitException("Unable to create JS editor", e);
    }
}

From source file:ch.entwine.weblounge.common.impl.util.TestUtils.java

/**
 * Parses the <code>HTTP</code> response body into a <code>DOM</code>
 * document.//from   ww w  . ja va 2s . co m
 * 
 * @param response
 *          the response
 * @return the parsed xml
 * @throws Exception
 *           if parsing fails
 */
public static Document parseXMLResponse(HttpResponse response) throws Exception {
    String responseXml = EntityUtils.toString(response.getEntity(), "utf-8");
    responseXml = StringEscapeUtils.unescapeHtml(responseXml);

    // Depending on whether it's an HTML page, let's make sure we end up with a
    // valid DOM
    Header contentTypeHeader = response.getFirstHeader("Content-Type");
    String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;

    Document doc = null;
    if ("text/html".equals(contentType)) {
        Tidy tidy = new Tidy();
        tidy.setOnlyErrors(true);
        tidy.setOutputEncoding("utf-8");
        doc = tidy.parseDOM(IOUtils.toInputStream(responseXml, "utf-8"), null);
    } else {
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
        factory.setNamespaceAware(true);
        DocumentBuilder builder = factory.newDocumentBuilder();
        doc = builder.parse(new ByteArrayInputStream(responseXml.getBytes("utf-8")));
    }
    return doc;
}

From source file:de.shadowhunt.subversion.internal.AbstractRepositoryCombinedOperationsIT.java

@Test
public void test01_AddMultipleFiles() throws Exception {
    final String content = "test";
    final Resource resourceA = prefix.append(Resource.create("fileA.txt"));
    final Resource resourceB = prefix.append(Resource.create("fileB.txt"));

    final Transaction transaction = repository.createTransaction();
    try {//from www.  ja  va2  s.  c o m
        repository.add(transaction, resourceA, true, IOUtils.toInputStream(content, AbstractHelper.UTF8));
        repository.add(transaction, resourceB, true, IOUtils.toInputStream(content, AbstractHelper.UTF8));
        repository.commit(transaction, "add " + resourceA + " " + resourceB);
    } finally {
        repository.rollbackIfNotCommitted(transaction);
    }

    final InputStream expectedA = IOUtils.toInputStream(content, AbstractHelper.UTF8);
    final InputStream actualA = repository.download(resourceA, Revision.HEAD);
    AbstractRepositoryDownloadIT.assertEquals("content must match", expectedA, actualA);

    final InputStream expectedB = IOUtils.toInputStream(content, AbstractHelper.UTF8);
    final InputStream actualB = repository.download(resourceB, Revision.HEAD);
    AbstractRepositoryDownloadIT.assertEquals("content must match", expectedB, actualB);
}

From source file:mitm.common.fetchmail.FetchmailManagerImpl.java

private void runExternalApplyProcess(String xml) throws IOException {
    List<String> cmd = new LinkedList<String>();

    cmd.add(externalApplyCommand.getPath());

    ProcessRunner runner = new ProcessRunner();

    runner.setTimeout(TIMEOUT);/*  w w w .j av a2 s.  c  o m*/

    /*
     * The XML will be piped to the process
     */
    runner.setInput(IOUtils.toInputStream(xml, CharacterEncoding.US_ASCII));

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    SizeLimitedOutputStream slos = new SizeLimitedOutputStream(bos, MAX_OUTPUT_LENGTH, true);

    runner.setError(slos);

    try {
        runner.run(cmd);
    } catch (IOException e) {
        /*
         * We would like to report the error message from the external program
         */
        String error = getFirstLine(bos);

        if (StringUtils.isNotBlank(error)) {
            throw new IOException(error);
        }

        throw e;
    }
}

From source file:com.hp.autonomy.searchcomponents.hod.view.HodViewServerService.java

private InputStream formatRawContent(final Document document) {
    final String body = "<h1>" + escapeAndAddLineBreaks(resolveTitle(document)) + "</h1>" + "<p>"
            + escapeAndAddLineBreaks(document.getContent()) + "</p>";

    return IOUtils.toInputStream(body, StandardCharsets.UTF_8);
}

From source file:mitm.common.postfix.SaslPasswordManager.java

private void setSaslPasswordContent(String content) throws IOException {
    List<String> cmd = new LinkedList<String>();

    cmd.add(externalCommand.getPath());//from   w w  w .  j a  va  2 s .c o m
    cmd.add("set");

    ProcessRunner runner = new ProcessRunner();

    runner.setTimeout(TIMEOUT);

    /*
     * The content will be piped to the process
     */
    runner.setInput(IOUtils.toInputStream(content, CharacterEncoding.US_ASCII));

    runner.run(cmd);
}