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:mitm.common.fetchmail.FetchmailConfigBuilderTest.java

@Test
public void testFetchmailConfigWriter() throws Exception {
    String input = "set syslog\n\n### START-AUTO-CONFIG ###\n" + "### END-AUTO-CONFIG ###\n\n## test";

    FetchmailConfig config = new FetchmailConfig();

    config.setPollInterval(5 * 60);/*w ww. j  av a2  s .c o  m*/
    config.setPostmaster("test\"@example.com");
    config.setCheckCertificate(true);

    Poll poll = new Poll();
    poll.setServer("example.com");
    poll.setAuthentication(Authentication.NTLM);
    poll.setFolder("ab\"cde\tf");
    poll.setUsername("&\"&&");
    poll.setIdle(true);
    poll.setProtocol(Protocol.IMAP);

    Poll poll2 = new Poll();
    poll2.setUIDL(false);
    poll2.setPassword("12&3");
    poll2.setPort(123);

    config.getPolls().add(poll);
    config.getPolls().add(poll2);

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    FetchmailConfigBuilder.createConfig(config, IOUtils.toInputStream(input, "US-ASCII"), bos);

    String result = new String(bos.toByteArray(), "US-ASCII");

    assertTrue(result.contains("sslcertck"));
    assertTrue(result.contains("poll \"example.com\""));
    assertTrue(result.contains("poll \"undefined\""));
    assertTrue(result.contains(" service 123 "));
    assertTrue(result.contains("set syslog"));
    assertTrue(result.contains(" no uidl "));
    assertTrue(result.contains(" no keep"));
    assertTrue(result.contains("password \"12&3\""));
    assertTrue(result.contains("postmaster \"test\\x22@example.com\""));
    assertTrue(result.contains("user \"&\\x22&&\""));
    assertTrue(result.contains("folder \"ab\\x22cdef\""));
    assertTrue(result.contains("## test"));
}

From source file:com.medvision360.medrecord.server.archetype.ArchetypeListServerResource.java

@Override
public void postArchetypeAsText(String adl) throws RecordException {
    String archetypeId = null;/*  w ww.  j a va 2  s  .  c  o  m*/
    try {
        try {
            if (adl == null || adl.isEmpty()) {
                throw new MissingParameterException(
                        "Provide a non-empty ADL containing the archetype definition");
            }

            MedRecordEngine engine = engine();
            ArchetypeParser parser = engine.getArchetypeParser("text/plain", "adl");
            WrappedArchetype archetype;
            try {
                archetype = parser.parse(IOUtils.toInputStream(adl, "UTF-8"));
            } catch (ParseException e) {
                Throwable root = e;
                int limit = 10, i = 0;
                while (e.getCause() != null && i < limit) {
                    root = e.getCause();
                    i++;
                }
                throw new ClientParseException(root.getMessage(), e);
            }
            archetypeId = archetype.getArchetype().getArchetypeId().getValue();
            engine.getArchetypeStore().insert(archetype);
        } catch (IOException e) {
            throw new IORecordException(e.getMessage(), e);
        }
        Events.append("INSERT", archetypeId, "ARCHETYPE", "postArchetype",
                String.format("Inserted archetype %s", archetypeId));
    } catch (RecordException | RuntimeException e) {
        Events.append("ERROR", archetypeId, "ARCHETYPE", "postArchetypeFailure",
                String.format("Failure to insert archetype %s: %s", archetypeId, e.getMessage()));
        throw e;
    }
}

From source file:energy.usef.core.util.XMLUtil.java

/**
 * Converts xml to an object after optional validation against the xsd.
 *
 * @param xml xml string/*from w  ww.ja v a  2s.co m*/
 * @param validate true when the xml needs to be validated
 * @return object corresponding to this xml
 */
public static Object xmlToMessage(String xml, boolean validate) {
    try (InputStream is = IOUtils.toInputStream(xml, UTF_8)) {
        Unmarshaller unmarshaller = CONTEXT.createUnmarshaller();

        if (validate) {
            // setup xsd validation
            SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);
            Schema schema = sf.newSchema(XMLUtil.class.getClassLoader().getResource(MESSAGING_XSD_FILE));

            unmarshaller.setSchema(schema);
        }

        return unmarshaller.unmarshal(is);
    } catch (JAXBException | IOException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TechnicalException("Invalid XML content: " + e.getMessage(), e);
    } catch (SAXException e) {
        LOGGER.error(e.getMessage(), e);
        throw new TechnicalException("Unable to read XSD schema", e);
    }
}

From source file:com.elsevier.xml.XPathProcessor.java

/**
 * Apply the xpathExpression to the specified string and return a serialized
 * response.//from   www  .ja  v a 2 s  . c  om
 * 
 * @param content
 *            String to which the xpathExpression will be applied
 * @param xpathExpression
 *            XPath expression to apply to the content
 * @return Serialized response from the evaluation.  If an error, the response will be "<error/>".
 */
public static String evaluateString(String content, String xpathExpression) {

    try {

        return evaluate(new StreamSource(IOUtils.toInputStream(content, CharEncoding.UTF_8)), xpathExpression);

    } catch (IOException e) {

        log.error("Problems processing the content.  " + e.getMessage(), e);
        return "<error/>";

    }

}

From source file:io.kamax.mxisd.threepid.connector.email.EmailSmtpConnector.java

@Override
public void send(String senderAddress, String senderName, String recipient, String content) {
    if (StringUtils.isBlank(senderAddress)) {
        throw new FeatureNotAvailable("3PID Email identity: sender address is empty - "
                + "You must set a value for notifications to work");
    }//  ww  w  .java  2 s  . c  o m

    if (StringUtils.isBlank(content)) {
        throw new InternalServerError("Notification content is empty");
    }

    try {
        InternetAddress sender = new InternetAddress(senderAddress, senderName);
        MimeMessage msg = new MimeMessage(session, IOUtils.toInputStream(content, StandardCharsets.UTF_8));
        msg.setHeader("X-Mailer", "mxisd"); // FIXME set version
        msg.setSentDate(new Date());
        msg.setFrom(sender);
        msg.setRecipients(Message.RecipientType.TO, recipient);
        msg.saveChanges();

        log.info("Sending invite to {} via SMTP using {}:{}", recipient, cfg.getHost(), cfg.getPort());
        SMTPTransport transport = (SMTPTransport) session.getTransport("smtp");
        transport.setStartTLS(cfg.getTls() > 0);
        transport.setRequireStartTLS(cfg.getTls() > 1);

        log.info("Connecting to {}:{}", cfg.getHost(), cfg.getPort());
        transport.connect(cfg.getHost(), cfg.getPort(), cfg.getLogin(), cfg.getPassword());
        try {
            transport.sendMessage(msg, InternetAddress.parse(recipient));
            log.info("Invite to {} was sent", recipient);
        } finally {
            transport.close();
        }
    } catch (UnsupportedEncodingException | MessagingException e) {
        throw new RuntimeException("Unable to send e-mail invite to " + recipient, e);
    }
}

From source file:com.cognifide.aet.job.common.collectors.source.SourceCollector.java

@Override
public final CollectorStepResult collect() throws ProcessingException {
    CollectorStepResult stepResult;/*from www  .ja v  a 2s. c o  m*/
    InputStream dataInputStream = null;
    try {
        byte[] content = getContent();
        final String pageSource = new String(content, CHAR_ENCODING);
        if (StringUtils.isBlank(pageSource)) {
            throw new ProcessingException("Page source is empty!");
        }
        dataInputStream = IOUtils.toInputStream(pageSource, CHAR_ENCODING);
        String resultId = artifactsDAO.saveArtifact(properties, dataInputStream, CONTENT_TYPE);
        stepResult = CollectorStepResult.newCollectedResult(resultId);

    } catch (Exception e) {
        throw new ProcessingException(e.getMessage(), e);
    } finally {
        IOUtils.closeQuietly(dataInputStream);
    }
    return stepResult;
}

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

@Test
public void testEscapedInputStream_tagWithText() throws Exception {
    final String xml = "<C:foo:bar>text</C:foo:bar>";
    final String expected = "<C:foo" + MARKER + "bar>text</C:foo" + MARKER + "bar>";
    final InputStream stream = IOUtils.toInputStream(xml, ResourcePropertyUtils.UTF8);

    final InputStream escapedStream = ResourcePropertyUtils.escapedInputStream(stream);
    final String escapedXml = IOUtils.toString(escapedStream, ResourcePropertyUtils.UTF8);

    Assert.assertEquals(expected, escapedXml);
}

From source file:ch.cyberduck.core.cryptomator.features.CryptoReadFeatureTest.java

@Test
public void testCalculations() throws Exception {
    final NullSession session = new NullSession(new Host(new TestProtocol())) {
        @Override// w  ww  . jav  a  2  s.c  om
        @SuppressWarnings("unchecked")
        public <T> T _getFeature(final Class<T> type) {
            if (type == Read.class) {
                return (T) new Read() {
                    @Override
                    public InputStream read(final Path file, final TransferStatus status,
                            final ConnectionCallback callback) throws BackgroundException {
                        final String masterKey = "{\n" + "  \"scryptSalt\": \"NrC7QGG/ouc=\",\n"
                                + "  \"scryptCostParam\": 16384,\n" + "  \"scryptBlockSize\": 8,\n"
                                + "  \"primaryMasterKey\": \"Q7pGo1l0jmZssoQh9rXFPKJE9NIXvPbL+HcnVSR9CHdkeR8AwgFtcw==\",\n"
                                + "  \"hmacMasterKey\": \"xzBqT4/7uEcQbhHFLC0YmMy4ykVKbuvJEA46p1Xm25mJNuTc20nCbw==\",\n"
                                + "  \"versionMac\": \"hlNr3dz/CmuVajhaiGyCem9lcVIUjDfSMLhjppcXOrM=\",\n"
                                + "  \"version\": 5\n" + "}";
                        return IOUtils.toInputStream(masterKey, Charset.defaultCharset());
                    }

                    @Override
                    public boolean offset(final Path file) throws BackgroundException {
                        return false;
                    }
                };
            }
            return super._getFeature(type);
        }
    };
    final Path home = new Path("/", EnumSet.of((Path.Type.directory)));
    final CryptoVault vault = new CryptoVault(home, new DisabledPasswordStore());
    assertEquals(home, vault.load(session, new DisabledPasswordCallback() {
        @Override
        public Credentials prompt(final Host bookmark, final String title, final String reason,
                final LoginOptions options) throws LoginCanceledException {
            return new VaultCredentials("vault");
        }
    }).getHome());
    CryptoReadFeature read = new CryptoReadFeature(null, null, vault);
    {
        assertEquals(0, read.chunk(0));
        assertEquals(0, read.chunk(1));
        assertEquals(1, read.chunk(32768));
        assertEquals(1, read.chunk(32769));
    }
    {
        assertEquals(88, read.align(1));
        assertEquals(88, read.align(88));
        assertEquals(88, read.align(89));
        assertEquals(88, read.align(15342));
        assertEquals(88, read.align(32767));
        assertEquals(88 + 48 + 32768, read.align(32768));
        assertEquals(88 + 48 + 32768, read.align(32769));
    }
    {
        assertEquals(24, read.position(24));
        assertEquals(0, read.position(0));
        assertEquals(0, read.position(32768));
        assertEquals(1, read.position(32769));
    }
    vault.close();
}

From source file:cool.pandora.modeller.ui.handlers.iiif.PatchResourceHandler.java

private static InputStream getResourceMetadata(final Map<String, BagInfoField> map, final String filename,
        final String formatName, final int iw, final int ih) {
    final MetadataTemplate metadataTemplate;
    final List<ResourceScope.Prefix> prefixes = Arrays.asList(new ResourceScope.Prefix(FedoraPrefixes.RDFS),
            new ResourceScope.Prefix(FedoraPrefixes.MODE), new ResourceScope.Prefix(IIIFPrefixes.DC),
            new ResourceScope.Prefix(IIIFPrefixes.SVCS), new ResourceScope.Prefix(IIIFPrefixes.EXIF),
            new ResourceScope.Prefix(IIIFPrefixes.DCTYPES));

    final ResourceScope scope = new ResourceScope().fedoraPrefixes(prefixes).filename(filename)
            .serviceURI(getServiceURI(map, filename)).formatName(formatName).imgHeight(ih).imgWidth(iw);

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

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

From source file:com.hortonworks.registries.storage.filestorage.TransactionTest.java

@Test
public void testRollback() throws Exception {
    String input;//w ww.  j a  va2  s .c o m

    try {
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME), "UTF-8");
        dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME);
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }

    try {
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        String update = input + " new text";
        dbFileStorage.upload(IOUtils.toInputStream(update, "UTF-8"), FILE_NAME);
        InputStream is = dbFileStorage.download(FILE_NAME);
        String output = IOUtils.toString(is, "UTF-8");
        Assert.assertEquals(update, output);
        throw new Exception();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
    }

    try {
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        InputStream is = dbFileStorage.download(FILE_NAME);
        String output = IOUtils.toString(is, "UTF-8");
        Assert.assertEquals(input, output);
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }
}