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:de.smartics.maven.plugin.jboss.modules.xml.XmlFragmentParser.java

/**
 * Parses the given XML fragment.//from w w  w.  j av  a  2 s . com
 *
 * @param xmlFragment the fragment to be parsed in UTF-8 encoding.
 * @return the parsed root element.
 * @throws IllegalArgumentException on any parsing problem.
 */
public Element parse(final String xmlFragment) throws IllegalArgumentException {
    try {
        final InputStream input = IOUtils.toInputStream(xmlFragment, "UTF-8");
        final Document document = builder.build(input);
        final Element root = document.getRootElement();
        return root.detach();
    } catch (final IOException e) {
        throw new IllegalStateException("UTF-8 encoding not supported on this platform.");
    } catch (final JDOMException e) {
        throw new IllegalArgumentException("Cannot parse XML fragment: " + xmlFragment, e);
    }
}

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

@Test
public void test01_AddFileAndFolder() throws Exception {
    final String content = "test";
    final Resource file = prefix.append(Resource.create("file_and_folder.txt"));
    final Resource folder = prefix.append(Resource.create("file_and_folder"));

    final Transaction transaction = repository.createTransaction();
    try {/*from   ww w . j  a v a 2  s.co  m*/
        repository.add(transaction, file, true, IOUtils.toInputStream(content, AbstractHelper.UTF8));
        repository.mkdir(transaction, folder, true);
        repository.commit(transaction, "add " + file + " " + folder);
    } finally {
        repository.rollbackIfNotCommitted(transaction);
    }

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

    final Info info = repository.info(folder, Revision.HEAD);
    Assert.assertTrue("folder exists", info.isDirectory());
}

From source file:com.adaptris.core.services.dynamic.ServiceFromDataInputParameter.java

@Override
public InputStream getInputStream(AdaptrisMessage m) throws Exception {
    Args.notNull(input, "input");
    return IOUtils.toInputStream(input.extract(m), m.getContentEncoding());
}

From source file:com.thruzero.domain.jpa.dao.JpaDataStoreContainer.java

@Override
public DataStoreEntity readEntity(String entityName) {
    EntityPath primaryKey = new EntityPath(containerPath, entityName);
    TextEnvelope inputsEnvelope = jpaTextEnvelopeDAO.getTextEnvelope(primaryKey);
    try {//from w ww. ja  v a 2  s.c o m
        DataStoreEntity data = new SimpleDataStoreEntity(
                IOUtils.toInputStream(inputsEnvelope.getData(), CharEncoding.UTF_8), primaryKey);
        return data;
    } catch (IOException e) {
        throw new RuntimeException("couldn't convert inputsEnvelope to InputStream.", e);
    }
}

From source file:mitm.common.security.ca.CSVRequestConverterTest.java

@Test
public void testDefaultValues() throws Exception {
    String input = "email, cn\r\n" + "test1@example.com,cn1\r\n";

    CSVRequestConverter converter = new CSVRequestConverter();

    List<RequestParameters> parameters = converter
            .convertCSV(IOUtils.toInputStream(input, CharacterEncoding.US_ASCII));

    assertNotNull(parameters);//www  .  j a v  a2  s. c o m
    assertEquals(1, parameters.size());

    RequestParameters request = parameters.get(0);

    assertEquals("test1@example.com", request.getEmail());
    assertEquals("EMAILADDRESS=test1@example.com, CN=cn1", request.getSubject().toString());
    assertEquals(0, request.getKeyLength());
    assertEquals(0, request.getValidity());
    assertNull(request.getCRLDistributionPoint());
    assertNull(request.getSignatureAlgorithm());
    assertNull(request.getCertificateRequestHandler());
}

From source file:com.alta189.deskbin.services.image.TwitterService.java

@Override
public String upload(BufferedImage image) throws ImageServiceException {
    try {//from  www .  j a va  2s  .  c  om
        ImageUpload upload = new ImageUploadFactory().getInstance(imageService,
                twitterService.getAuthorization());
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "png", baos);
        InputStream input = IOUtils.toInputStream(IOUtils.toString(baos.toByteArray(), "UTF-8"), "UTF-8");
        return upload.upload(FILENAME, input);
    } catch (Exception e) {
        throw new ImageServiceException(e);
    }
}

From source file:mitm.djigzo.web.utils.SetDefaultSystemPropertiesServletContextListener.java

@Override
public void contextInitialized(ServletContextEvent contextEvent) {
    String propertiesParam = contextEvent.getServletContext().getInitParameter("djigzo.system.properties");

    if (propertiesParam != null) {
        Properties properties = new Properties();

        try {//from   w w  w.j a v  a2s.c o  m
            properties.load(IOUtils.toInputStream(propertiesParam, "UTF-8"));

            for (Map.Entry<Object, Object> entry : properties.entrySet()) {
                if (System.getProperty((String) entry.getKey()) == null) {
                    System.setProperty((String) entry.getKey(), (String) entry.getValue());
                }
            }
        } catch (IOException e) {
            logger.error("Error loading properties.", e);
        }
    } else {
        logger.warn("property djigzo.systemproperties.default is missing.");
    }
}

From source file:com.adaptris.core.services.dynamic.ServiceFromCache.java

@Override
public InputStream getInputStream(AdaptrisMessage msg) throws Exception {
    Args.notBlank(getKey(), "key");
    Cache cache = getConnection().retrieveConnection(CacheConnection.class).retrieveCache();
    String service = (String) cache.get(msg.resolve(getKey()));
    return IOUtils.toInputStream(service, msg.getContentEncoding());
}

From source file:co.cask.hydrator.plugin.batch.CopybookRecordReader.java

@Override
public void initialize(InputSplit split, TaskAttemptContext context) throws IOException, InterruptedException {
    // Get configuration
    Configuration conf = context.getConfiguration();
    int fileStructure = net.sf.JRecord.Common.Constants.IO_FIXED_LENGTH;
    Path path = new Path(conf.get(CopybookInputFormat.COPYBOOK_INPUTFORMAT_DATA_HDFS_PATH));
    FileSystem fs = FileSystem.get(path.toUri(), conf);
    // Create input stream for the COBOL copybook contents
    InputStream inputStream = IOUtils
            .toInputStream(conf.get(CopybookInputFormat.COPYBOOK_INPUTFORMAT_CBL_CONTENTS), "UTF-8");
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
    try {/*w  ww  .ja v  a 2 s  .c  o m*/
        externalRecord = CopybookIOUtils.getExternalRecord(bufferedInputStream);
        recordByteLength = CopybookIOUtils.getRecordLength(externalRecord, fileStructure);

        LineProvider lineProvider = LineIOProvider.getInstance().getLineProvider(fileStructure,
                CopybookIOUtils.FONT);
        reader = LineIOProvider.getInstance().getLineReader(fileStructure, lineProvider);
        LayoutDetail copybook = CopybookIOUtils.getLayoutDetail(externalRecord);

        org.apache.hadoop.mapreduce.lib.input.FileSplit fileSplit = (org.apache.hadoop.mapreduce.lib.input.FileSplit) split;

        start = fileSplit.getStart();
        end = start + fileSplit.getLength();

        BufferedInputStream fileIn = new BufferedInputStream(fs.open(fileSplit.getPath()));
        // Jump to the point in the split at which the first complete record of the split starts,
        // if not the first InputSplit
        if (start != 0) {
            position = start - (start % recordByteLength) + recordByteLength;
            fileIn.skip(position);
        }
        reader.open(fileIn, copybook);

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

From source file:edu.lternet.pasta.portal.search.BrowseGroup.java

public static BrowseGroup generateKeywordCache() {
    BrowseGroup controlledVocabulary = new BrowseGroup("Controlled Vocabulary");
    BrowseGroup lterSiteCache = generateLterSiteCache();
    controlledVocabulary.addBrowseGroup(lterSiteCache);

    try {// w  ww .j a  v  a2 s . c  o m
        String topTermsXML = ControlledVocabularyClient.webServiceFetchTopTerms();
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        InputStream inputStream = IOUtils.toInputStream(topTermsXML, "UTF-8");
        Document document = documentBuilder.parse(inputStream);
        Element documentElement = document.getDocumentElement();
        NodeList documentNodeList = documentElement.getElementsByTagName("term");

        for (int i = 0; i < documentNodeList.getLength(); i++) {
            Node documentNode = documentNodeList.item(i);
            NodeList childNodes = documentNode.getChildNodes();
            String termId = null;
            String value = null;

            for (int j = 0; j < childNodes.getLength(); j++) {

                Node childNode = childNodes.item(j);
                if (childNode instanceof Element) {
                    Element childElement = (Element) childNode;
                    if (childElement.getTagName().equals("term_id")) {
                        Text text = (Text) childElement.getFirstChild();
                        termId = text.getData().trim();
                    } else if (childElement.getTagName().equals("string")) {
                        Text text = (Text) childElement.getFirstChild();
                        value = text.getData().trim();
                    }
                }
            }

            BrowseGroup topTerm = new BrowseGroup(value);
            controlledVocabulary.addBrowseGroup(topTerm);
            topTerm.setTermId(termId);
            topTerm.setHasMoreDown("1");
            topTerm.addFetchDownElements();
        }
    } catch (Exception e) {
        logger.error("Exception:\n" + e.getMessage());
        e.printStackTrace();
        /*
         * By returning null, we let callers know that there was a problem
         * refreshing the browse cache, so callers will know not to
         * overwrite the previous results.
         */
        controlledVocabulary = null;
    }

    return controlledVocabulary;
}