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:cool.pandora.modeller.ui.handlers.text.PatchWordsHandler.java

/**
 * getWordMetadata./*from   ww  w .  ja  va  2s  .co  m*/
 *
 * @param canvasRegionURI  String
 * @param wordContainerURI String
 * @param chars            String
 * @return InputStream
 */
private static InputStream getWordMetadata(final String canvasRegionURI, final String wordContainerURI,
        final String chars) {
    final MetadataTemplate metadataTemplate;
    final List<WordScope.Prefix> prefixes = Arrays.asList(new WordScope.Prefix(FedoraPrefixes.RDFS),
            new WordScope.Prefix(FedoraPrefixes.MODE), new WordScope.Prefix(IIIFPrefixes.OA),
            new WordScope.Prefix(IIIFPrefixes.CNT), new WordScope.Prefix(IIIFPrefixes.SC),
            new WordScope.Prefix(IIIFPrefixes.DCTYPES));

    final WordScope scope = new WordScope().fedoraPrefixes(prefixes).canvasURI(canvasRegionURI)
            .resourceContainerURI(wordContainerURI).chars(chars.replace("\"", "\\\""));

    metadataTemplate = MetadataTemplate.template().template("template/sparql-update-word" + ".mustache")
            .scope(scope).throwExceptionOnFailure().build();

    final String metadata = unescapeXml(metadataTemplate.render());
    return IOUtils.toInputStream(metadata, UTF_8);
}

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

@Test
public void testSaveEmailAndNotify_correct_config() throws Exception {
    // GIVEN I have a server accurately configured (relay domains)
    MailServerModel mailServerModel = new MailServerModel();
    ServerConfiguration serverConfiguration = new ServerConfiguration().relayDomains("data.org");

    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/*from  www.  ja va 2  s.c o m*/
    Assert.assertEquals(1, mailServerModel.getEmailModels().size());
    EmailModel emailModel = mailServerModel.getEmailModels().get(0);
    assertNotNull(emailModel);

    //
}

From source file:com.adaptris.mail.ApacheMailClient.java

private MimeMessage createMimeMessage(Session session, Reader src) throws IOException, MessagingException {
    MimeMessage result = null;/*www.java  2s.  com*/
    StringWriter writer = new StringWriter();
    try (BufferedReader bufferedReader = new BufferedReader(src)) {
        IOUtils.copy(bufferedReader, writer);
    }
    try (InputStream mimeMessageInput = IOUtils.toInputStream(writer.toString(), Charset.defaultCharset())) {
        result = new MimeMessage(session, mimeMessageInput);
    }
    return result;
}

From source file:com.adobe.aem.importer.impl.GitListenerImpl.java

public void handleEvent(final Event osgiEvent) {
    Project gitProject = (Project) osgiEvent.getProperty(GitHubPushConstants.EVT_PROJECT);
    GitHubPushEvent gitHubPushEvent = (GitHubPushEvent) osgiEvent.getProperty(GitHubPushConstants.EVT_GHEVENT);

    URI gitRepoUrl = gitHubPushEvent.getRepoUrl();
    String sourcePath = DocImporter.GIT_REPOS_FOLDER_PATH + "/" + gitRepoUrl.getHost() + gitRepoUrl.getPath();

    List<String> added = gitHubPushEvent.getAddedFileNames();
    List<String> modified = gitHubPushEvent.getModifiedFileNames();
    List<String> deleted = gitHubPushEvent.getDeletedFileNames();
    modified.addAll(added);/*from  w  w  w  .j a v  a 2s  .  c  o  m*/

    Session session;
    try {
        session = repository.loginAdministrative(null);
        for (String path : modified) {
            String[] split = path.split("/");
            String fileName = split[split.length - 1];
            int lastForwardSlashPos = path.lastIndexOf("/");

            String parentPath = sourcePath;
            if (lastForwardSlashPos > 0) {
                parentPath = parentPath + "/" + path.substring(0, lastForwardSlashPos);
            }

            File gitFile = gitProject.getFile(EncodeUtil.escapePath(path));
            Node parentNode = JcrUtils.getOrCreateByPath(parentPath, "nt:folder", "nt:folder", session, true);
            InputStream in = IOUtils.toInputStream(gitFile.getContent(), "UTF-8");
            JcrUtils.putFile(parentNode, fileName, "application/xml", in);
            session.save();
        }

        for (String path : deleted) {
            String deleteNodePath = sourcePath + "/" + path;
            if (session.nodeExists(deleteNodePath)) {
                session.getNode(deleteNodePath).remove();
                session.save();
            }
        }
        docImporter.doImport(sourcePath);
    } catch (Exception e) {
        log.error("Exception", e);
    }
}

From source file:cat.calidos.morfeu.model.injection.URIToParsedModule.java

@Produces
@Named("FetchedRawContent")
public static InputStream fetchedRawContent(@Named("FetchableContentURI") URI uri) throws FetchingException {

    // if uri is absolute we retrieve it, otherwise we assume it's a local relative file

    try {//from  w w w  .  j  av  a 2  s.c om
        if (uri.isAbsolute()) {
            log.info("Fetching absolute content uri '{}' to parse", uri);
            return IOUtils.toInputStream(IOUtils.toString(uri, Config.DEFAULT_CHARSET), Config.DEFAULT_CHARSET);
        } else {
            log.info("Fetching relative content uri '{}' to parse, assuming file", uri);
            return FileUtils.openInputStream(new File(uri.toString()));
        }
    } catch (IOException e) {
        log.error("Could not fetch '{}' ({}", uri, e);
        throw new FetchingException("Problem when fetching '" + uri + "'", e);
    }
}

From source file:com.telefonica.euro_iaas.paasmanager.rest.auth.OpenStackAuthenticationTokenTest.java

@Test
public void getCredentialsTest() throws AuthenticationConnectionException, IOException {

    OpenStackAuthenticationToken openStackAuthenticationToken;
    ArrayList<Object> params = new ArrayList<Object>();
    HttpClient httpClient;//from w ww.  j av  a  2s  .  c o m
    HttpResponse response;
    StatusLine statusLine;
    HttpEntity httpEntity;
    InputStream is;

    String payload = "<access xmlns=\"http://docs.openstack.org/identity/api/v2.0\"><token "
            + "expires=\"2015-07-09T15:16:07Z\" id=\"35b208abaf09707c5fed8e54af9a48b8\"><tenant "
            + "enabled=\"true\" id=\"00000000000000000000000000000001\" name=\"00000000000000000000000000000001\"/>"
            + "</token><serviceCatalog><endpoints><adminURL>http://130.206.80.58:8774/v2/undefined</adminURL>"
            + "<region>Trento</region><internalURL>http://130.206.80.58:8774/v2/undefined</internalURL>";

    httpClient = mock(HttpClient.class);
    response = mock(HttpResponse.class);
    statusLine = mock(StatusLine.class);
    httpEntity = mock(HttpEntity.class);
    is = IOUtils.toInputStream(payload, "UTF-8");

    params.add("url");
    params.add("tenant");
    params.add("user");
    params.add("passw");
    params.add(httpClient);
    params.add(new Long(3));

    openStackAuthenticationToken = new OpenStackAuthenticationToken(params);

    Header header = new Header() {

        @Override
        public String getValue() {
            return "Fri, 21 Nov 2014 12:30:54 GMT";
        }

        @Override
        public String getName() {
            return "Date";
        }

        @Override
        public HeaderElement[] getElements() {
            // TODO Auto-generated method stub
            return null;
        }
    };
    Header[] headers = new Header[] { header };

    when(statusLine.getStatusCode()).thenReturn(200);
    when(response.getStatusLine()).thenReturn(statusLine);
    when(response.getEntity()).thenReturn(httpEntity);
    when(httpEntity.getContent()).thenReturn(is);
    when(httpClient.execute(any(HttpPost.class))).thenReturn(response);
    when(response.getHeaders(anyString())).thenReturn(headers);

    openStackAuthenticationToken.getCredentials();

    verify(httpClient, times(1)).execute(any(HttpPost.class));

}

From source file:com.formkiq.core.service.notification.MailSenderServiceTest.java

/**
 * testLoadMailProperties01().//from w  w w  .j  a va2 s . co  m
 * @throws Exception Exception
 */
@Test
public void testLoadMailProperties01() throws Exception {
    // given
    String ls = System.getProperty("line.separator");

    String source = "mail.host=smtp.gmail.com" + ls + "mail.port=587" + ls + "mail.username=test@formkiq.com"
            + ls + "mail.password=test" + ls + "mail.smtp.auth=true" + ls + "mail.smtp.starttls.enable=true"
            + ls + "mail.smtp.quitwait=false";

    InputStream in = IOUtils.toInputStream(source, "UTF-8");
    Properties prop = new Properties();
    prop.load(in);

    // when
    Session se = Session.getDefaultInstance(prop, null);
    Provider prov = se.getProvider("smtp");

    Class<?> clazz = Class.forName(prov.getClassName());

    // then
    assertNotNull(clazz);
    in.close();
}

From source file:com.spartasystems.holdmail.smtp.OutgoingMailSender.java

protected Message initializeMimeMessage(String rawBody, Session session) throws MessagingException {
    return new MimeMessage(session, IOUtils.toInputStream(rawBody, StandardCharsets.UTF_8));
}

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

@Test
public void test01_AddFileAndSetProperties() throws Exception {
    final String content = "test";
    final Resource resource = prefix.append(Resource.create("file_and_properties.txt"));
    final ResourceProperty property = new ResourceProperty(Type.SUBVERSION_CUSTOM, "foo", "bar");

    final Transaction transaction = repository.createTransaction();
    try {/*w ww.ja va2s  .  c o  m*/
        repository.add(transaction, resource, true, IOUtils.toInputStream(content, AbstractHelper.UTF8));
        repository.propertiesSet(transaction, resource, property);
        Assert.assertEquals("change set must contain: " + resource, Status.ADDED,
                transaction.getChangeSet().get(resource));
        repository.commit(transaction, "add " + resource);
    } finally {
        repository.rollbackIfNotCommitted(transaction);
    }

    final InputStream expected = IOUtils.toInputStream(content, AbstractHelper.UTF8);
    final InputStream actual = repository.download(resource, Revision.HEAD);
    AbstractRepositoryDownloadIT.assertEquals("content must match", expected, actual);

    final Info info = repository.info(resource, Revision.HEAD);
    final ResourceProperty[] actualProperties = info.getProperties();
    Assert.assertEquals("expected number of properties", 1, actualProperties.length);
    Assert.assertEquals("property must match", property, actualProperties[0]);
}

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

@Test(expected = SubversionException.class)
public void test00_invalid() throws Exception {
    final Resource resource = prefix.append(Resource.create("invalid.txt"));

    final Transaction transaction = repository.createTransaction();
    try {//from ww w  . j  av  a2s  .c om
        Assert.assertTrue("transaction must be active", transaction.isActive());
        transaction.invalidate();
        Assert.assertFalse("transaction must not be active", transaction.isActive());
        repository.add(transaction, resource, false, IOUtils.toInputStream("test", AbstractHelper.UTF8));
        Assert.fail("must not complete");
    } finally {
        repository.rollbackIfNotCommitted(transaction);
    }
}