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.security.ca.CSVRequestConverterTest.java

@Test(expected = RequestConverterException.class)
public void testDuplicateEmails() throws Exception {
    String input = "email, organisation, COMMONNAME, firstname, lastname\r\n"
            + "test1@example.com,org,  cn1  , firstname1, lastname1\r\n"
            + "test1@example.com,org,  cn1  , firstname1, lastname1";

    CSVRequestConverter converter = new CSVRequestConverter();

    converter.convertCSV(IOUtils.toInputStream(input, CharacterEncoding.US_ASCII));
}

From source file:ch.cyberduck.core.cryptomator.impl.CryptoVaultTest.java

@Test
public void testLoad() throws Exception {
    final NullSession session = new NullSession(new Host(new TestProtocol())) {
        @Override//from   w w  w .  j  a va  2s  .c o m
        @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());
    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");
        }
    });
    assertEquals(Vault.State.open, vault.getState());
    assertNotSame(home, vault.encrypt(session, home));
    assertEquals(vault.encrypt(session, home), vault.encrypt(session, home));
    final Path directory = new Path(home, "dir", EnumSet.of(Path.Type.directory));
    assertNull(directory.attributes().getVault());
    assertEquals(home, vault.encrypt(session, directory).attributes().getVault());
    assertEquals(home, directory.attributes().getVault());
    assertEquals(vault.encrypt(session, directory), vault.encrypt(session, directory));
    assertEquals(new Path(home, directory.getName(), EnumSet.of(Path.Type.directory, Path.Type.decrypted)),
            vault.decrypt(session, vault.encrypt(session, directory, true)));
    final Path placeholder = new Path(home, "placeholder",
            EnumSet.of(Path.Type.directory, Path.Type.placeholder));
    assertTrue(vault.encrypt(session, placeholder, true).getType().contains(Path.Type.placeholder));
    assertTrue(vault.decrypt(session, vault.encrypt(session, placeholder, true)).getType()
            .contains(Path.Type.placeholder));
    assertEquals(
            new Path(home, placeholder.getName(),
                    EnumSet.of(Path.Type.directory, Path.Type.placeholder, Path.Type.decrypted)),
            vault.decrypt(session, vault.encrypt(session, placeholder, true)));
    assertNotEquals(vault.encrypt(session, directory), vault.encrypt(session, directory, true));
    assertEquals(vault.encrypt(session, directory).attributes().getDirectoryId(),
            vault.encrypt(session, directory).attributes().getDirectoryId());
    assertEquals(vault.encrypt(session, vault.encrypt(session, directory)).attributes().getDirectoryId(),
            vault.encrypt(session, vault.encrypt(session, directory)).attributes().getDirectoryId());
    assertNull(vault.encrypt(session, directory, true).attributes().getDirectoryId());
    assertNull(vault.encrypt(session, vault.encrypt(session, directory), true).attributes().getDirectoryId());
    assertNotEquals(vault.encrypt(session, directory).attributes().getDirectoryId(),
            vault.encrypt(session, directory, true).attributes().getDirectoryId());

    vault.close();
    assertEquals(Vault.State.closed, vault.getState());
}

From source file:com.github.xmltopdf.JasperPdfGenerator.java

private void createDocument(List<String> templateNames, List<String> xmlFileNames, ByteArrayOutputStream os,
        DocType docType) {/*from w  ww.jav  a 2s  .  c  o m*/
    List<JasperPrint> jasperPrints = new ArrayList<JasperPrint>();
    InputStream fileIs = null;
    InputStream stringIs = null;
    if (!xmlFileNames.isEmpty()) {
        xmlTag = XMLDoc.from(MergeXml.merge(xmlFileNames), true);
    }
    try {
        for (String templateName : templateNames) {
            try {
                fileIs = new FileInputStream(templateNames.get(0));
                String contents = applyVelocityTemplate(IOUtils.toString(fileIs, "UTF-8"));
                stringIs = IOUtils.toInputStream(contents, "UTF-8");
                JasperReport jasperReport = JasperCompileManager.compileReport(stringIs);
                jasperPrints.add(
                        JasperFillManager.fillReport(jasperReport, new HashMap(), new JREmptyDataSource()));
            } finally {
                IOUtils.closeQuietly(fileIs);
                IOUtils.closeQuietly(stringIs);
            }
        }
        JasperPrint jasperPrint = jasperPrints.get(0);
        for (int index = 1; index < jasperPrints.size(); index += 1) {
            List<JRPrintPage> pages = jasperPrints.get(index).getPages();
            for (JRPrintPage page : pages) {
                jasperPrint.addPage(page);
            }
        }
        switch (docType) {
        case PDF:
            JasperExportManager.exportReportToPdfStream(jasperPrint, os);
            break;
        case RTF:
            JRRtfExporter rtfExporter = new JRRtfExporter();
            rtfExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            rtfExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
            rtfExporter.setParameter(JRExporterParameter.CHARACTER_ENCODING, "UTF-8");
            rtfExporter.exportReport();
            break;
        case XLS:
            JRXlsExporter xlsExporter = new JRXlsExporter();
            xlsExporter.setParameter(JRXlsExporterParameter.JASPER_PRINT, jasperPrint);
            xlsExporter.setParameter(JRXlsExporterParameter.OUTPUT_STREAM, os);
            xlsExporter.setParameter(JRXlsExporterParameter.IS_ONE_PAGE_PER_SHEET, Boolean.TRUE);
            //                    xlsExporter.setParameter(JRXlsExporterParameter.IS_AUTO_DETECT_CELL_TYPE, Boolean.TRUE);
            xlsExporter.setParameter(JRXlsExporterParameter.IS_WHITE_PAGE_BACKGROUND, Boolean.FALSE);
            xlsExporter.setParameter(JRXlsExporterParameter.IS_REMOVE_EMPTY_SPACE_BETWEEN_ROWS, Boolean.TRUE);
            xlsExporter.exportReport();
            break;
        case ODT:
            JROdtExporter odtExporter = new JROdtExporter();
            odtExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            odtExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
            odtExporter.exportReport();
            break;
        case PNG:
            BufferedImage pageImage = new BufferedImage((int) (jasperPrint.getPageWidth() * ZOOM_2X + 1),
                    (int) (jasperPrint.getPageHeight() * ZOOM_2X + 1), BufferedImage.TYPE_INT_RGB);
            JRGraphics2DExporter exporter = new JRGraphics2DExporter();
            exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            exporter.setParameter(JRGraphics2DExporterParameter.GRAPHICS_2D, pageImage.getGraphics());
            exporter.setParameter(JRGraphics2DExporterParameter.ZOOM_RATIO, ZOOM_2X);
            exporter.setParameter(JRExporterParameter.PAGE_INDEX, Integer.valueOf(0));
            exporter.exportReport();
            ImageIO.write(pageImage, "png", os);
            break;
        case HTML:
            JRHtmlExporter htmlExporter = new JRHtmlExporter();
            htmlExporter.setParameter(JRHtmlExporterParameter.JASPER_PRINT, jasperPrint);
            htmlExporter.setParameter(JRHtmlExporterParameter.OUTPUT_STREAM, os);
            htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_URI, "img/");
            htmlExporter.setParameter(JRHtmlExporterParameter.IMAGES_DIR, new java.io.File("img"));
            htmlExporter.setParameter(JRHtmlExporterParameter.IS_OUTPUT_IMAGES_TO_DIR, Boolean.TRUE);
            htmlExporter.setParameter(JRHtmlExporterParameter.ZOOM_RATIO, ZOOM_2X);
            htmlExporter.exportReport();
            break;
        case DOCX:
            JRDocxExporter docxExporter = new JRDocxExporter();
            docxExporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
            docxExporter.setParameter(JRExporterParameter.OUTPUT_STREAM, os);
            docxExporter.exportReport();
            break;
        default:
            break;
        }
    } catch (Exception ex) {
        LOG.error(this, ex, ex.getMessage());
    } finally {
        IOUtils.closeQuietly(os);
    }
}

From source file:com.norconex.commons.lang.io.CachedStreamFactory.java

public CachedInputStream newInputStream(String content) {
    InputStream is = null;//from w  w w . j a v  a 2  s.  com
    try {
        is = IOUtils.toInputStream(content, CharEncoding.UTF_8);
    } catch (IOException e) {
        LOG.error("Could not get input stream with UTF-8 encoding. " + "Trying with default encoding.", e);
        is = IOUtils.toInputStream(content);
    }
    return registerStream(new CachedInputStream(this, is, cacheDirectory));
}

From source file:com.spartasystems.holdmail.mapper.MessageSummaryMapperTest.java

@Test
public void shouldMapToMessageSummary() throws Exception {

    MimeBodyParts expectedBodyParts = mock(MimeBodyParts.class);

    ArgumentCaptor<InputStream> streamCaptor = ArgumentCaptor.forClass(InputStream.class);
    when(mimeBodyParserMock.findAllBodyParts(streamCaptor.capture())).thenReturn(expectedBodyParts);

    Message message = new Message(MESSAGE_ID, IDENTIFIER, SUBJECT, SENDER_MAIL, RECEIVED, SENDER_HOST,
            MESSAGE_SIZE, RAW_CONTENT, RECIPIENTS, HEADERS);

    MessageSummary summary = messageSummaryMapper.toMessageSummary(message);
    assertThat(summary.getMessageId()).isEqualTo(MESSAGE_ID);
    assertThat(summary.getIdentifier()).isEqualTo(IDENTIFIER);
    assertThat(summary.getSubject()).isEqualTo(SUBJECT);
    assertThat(summary.getSenderEmail()).isEqualTo(SENDER_MAIL);
    assertThat(summary.getReceivedDate()).isEqualTo(RECEIVED);
    assertThat(summary.getSenderHost()).isEqualTo(SENDER_HOST);
    assertThat(summary.getMessageSize()).isEqualTo(MESSAGE_SIZE);
    assertThat(summary.getRecipients()).isEqualTo("recip1,recip2");
    assertThat(summary.getMessageRaw()).isEqualTo(RAW_CONTENT);
    assertThat(summary.getMessageHeaders()).isEqualTo(HEADERS);

    assertThat(IOUtils.contentEquals(streamCaptor.getValue(), IOUtils.toInputStream(RAW_CONTENT, UTF_8)));

    MimeBodyParts actualParts = Whitebox.getInternalState(summary, "mimeBodyParts");
    assertThat(actualParts).isEqualTo(expectedBodyParts);

}

From source file:com.adaptris.core.marshaller.xstream.XStreamUtilsTest.java

@Test
public void testGetClasses() throws Exception {
    StringWriter sw = new StringWriter();
    try (PrintWriter pw = new PrintWriter(sw)) {
        pw.println(Adapter.class.getName());
        pw.println(ServiceList.class.getName());
        pw.println("hello.world");
    }//from w w  w  . j  ava2s  .co m
    try (InputStream in = IOUtils.toInputStream(sw.toString(), Charset.defaultCharset())) {
        List<Class<?>> classes = getClasses(in);
        assertEquals(2, classes.size());
    }
}

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

@Test
public void testUpdate() throws Exception {
    try {/*from www.  jav a 2s.co  m*/
        transactionManager.beginTransaction(TransactionIsolation.SERIALIZABLE);
        String input = IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(FILE_NAME),
                "UTF-8");
        dbFileStorage.upload(IOUtils.toInputStream(input, "UTF-8"), FILE_NAME);
        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);
        transactionManager.commitTransaction();
    } catch (Exception e) {
        transactionManager.rollbackTransaction();
        throw e;
    }
}

From source file:com.telefonica.euro_iaas.sdc.pupperwrapper.services.tests.ActionsServiceTest.java

@Before
public void setUpMock() throws Exception {
    catalogManagerMongo = mock(CatalogManagerMongoImpl.class);

    FileAccessService fileAccessService = mock(FileAccessServiceImpl.class);

    processBuilderFactory = mock(ProcessBuilderFactory.class);

    response = mock(HttpResponse.class);
    entity = mock(HttpEntity.class);
    statusLine = mock(StatusLine.class);
    HttpClient httpClient = mock(HttpClient.class);

    when(httpClient.execute((HttpUriRequest) Mockito.anyObject())).thenReturn(response);
    when(response.getEntity()).thenReturn(entity);
    String source = "";
    InputStream in = IOUtils.toInputStream(source, "UTF-8");
    when(entity.getContent()).thenReturn(in);
    when(response.getStatusLine()).thenReturn(statusLine);

    actionsService = new ActionServiceImpl4Test();
    actionsService.setCatalogManager(catalogManagerMongo);
    actionsService.setFileAccessService(fileAccessService);
    actionsService.setProcessBuilderFactory(processBuilderFactory);

    actionsService.setHttpClient(httpClient);

    node1 = new Node();
    node1.setGroupName("testGroup");
    node1.setId("1");
    Software soft1 = new Software();
    soft1.setName("testSoft");
    soft1.setAction(Action.INSTALL);
    soft1.setVersion("1.0.0");
    node1.addSoftware(soft1);/*from www . ja va2 s.  com*/

    node1Modified = new Node();
    node1Modified.setGroupName("testGroup");
    node1Modified.setId("1");
    Software soft1Modified = new Software();
    soft1Modified.setName("testSoft");
    soft1Modified.setAction(Action.INSTALL);
    soft1Modified.setVersion("2.0.0");
    node1.addSoftware(soft1Modified);

    attribute1 = new Attribute("user", "pepito");
    attributeList = new ArrayList<Attribute>();
    attributeList.add(attribute1);

}

From source file:com.htmlhifive.tools.wizard.utils.H5IOUtils.java

/**
 * ????. ${PROJECT_NAME}???????./*from   www  .j  av a2s.  co  m*/
 * 
 * @param shell 
 * @param projectHandle ?
 * @param fileName ??
 * @param varNames ??
 */
private static void convertName(Shell shell, IProject projectHandle, String fileName, String[] varNames,
        String[] varValues) {

    final IFile file = projectHandle.getFile(new Path(fileName));
    if (!file.isAccessible()) {
        return;
    }

    InputStream is = null;
    InputStream is2 = null;
    try {
        is = file.getContents();
        String text = IOUtils.toString(is, file.getCharset());
        for (int i = 0; i < varNames.length; i++) {
            text = StringUtils.replace(text, "${" + varNames[i] + "}", varValues[i]);
        }
        is2 = IOUtils.toInputStream(text, file.getCharset());
        file.setContents(is2, true, true, null);

    } catch (IOException e) {
        H5LogUtils.putLog(e, Messages.SE0024, fileName);
        //H5LogUtils.showLog(e, Messages.SE0022, Messages.SE0024, fileName);
    } catch (CoreException e) {
        H5LogUtils.putLog(e, Messages.SE0024, fileName);
        //H5LogUtils.showLog(e, Messages.SE0022, Messages.SE0024, fileName);
    } finally {
        IOUtils.closeQuietly(is);
        IOUtils.closeQuietly(is2);
    }
}

From source file:ch.cyberduck.core.cryptomator.impl.CryptoDirectoryProviderTest.java

@Test
public void testToEncryptedDirectory() throws Exception {
    final Path home = new Path("/vault", EnumSet.of(Path.Type.directory));
    final NullSession session = new NullSession(new Host(new TestProtocol())) {
        @Override//w  w  w  .j  av a2  s  .co m
        @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 CryptoVault vault = new CryptoVault(home, new DisabledPasswordStore());
    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");
        }
    });
    final CryptoDirectoryProvider provider = new CryptoDirectoryProvider(home, vault);
    assertNotNull(provider.toEncrypted(session, null, home));
    final Path f = new Path("/vault/f", EnumSet.of(Path.Type.directory));
    assertNotNull(provider.toEncrypted(session, null, f));
    assertEquals(provider.toEncrypted(session, null, f), provider.toEncrypted(session, null, f));
}