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.medvision360.medrecord.tools.cliclient.RemoteArchetypeStore.java

@Override
public WrappedArchetype get(ArchetypeID archetypeID) throws NotFoundException, IOException, ParseException {
    String archetypeIdString = archetypeID.getValue();
    ArchetypeResource resource = resource(archetypeIdString);
    String archetypeAsString;//  www .  j av a2 s.  c o  m
    try {
        ArchetypeResult result = resource.getArchetype();
        archetypeAsString = result.getAdl();
    } catch (RecordException e) {
        if (e instanceof NotFoundException) {
            throw (NotFoundException) e;
        }
        if (e instanceof ParseException) {
            throw (ParseException) e;
        }
        throw new IOException(e);
    }
    WrappedArchetype archetype = m_archetypeParser.parse(IOUtils.toInputStream(archetypeAsString, "UTF-8"));
    return archetype;
}

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

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

    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(0, mailServerModel.getEmailModels().size());

    ///*from w w w. j  a  v a2s .  c  o  m*/
}

From source file:ca.nines.ise.dom.DOMStream.java

/**
 * Constructs a DOMString from a string. The resulting DOM source will be
 * "#STRING".//from w ww . j  av a  2  s  .c o  m
 *
 * @param input The string to parse.
 *
 * @throws java.io.IOException
 */
public DOMStream(String input) throws IOException {
    this(IOUtils.toInputStream(input, "UTF-8"), "#STRING");
}

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

@Test
public void testAllowDuplicateEmails() 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.setAllowDuplicates(true);//from w ww.  ja  v a 2  s .  c o m

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

From source file:cool.pandora.modeller.ui.handlers.common.TextSequenceMetadata.java

/**
 * getListSequenceMetadata.//from w ww .  j a v a  2  s .c o  m
 *
 * @param resourceIDList      Map
 * @param listURI             String
 * @param resourceTargetMap   Map
 * @param collectionPredicate String
 * @param listServiceBaseURI  String
 * @return InputStream
 */
public static InputStream getListSequenceMetadata(final Map<String, List<String>> resourceIDList,
        final String listURI, final Map<String, String> resourceTargetMap, final String collectionPredicate,
        final String listServiceBaseURI) {
    final ArrayList<String> idList = new ArrayList<>(resourceIDList.get(listURI));

    final ResourceCollectionWriter collectionWriter;
    collectionWriter = ResourceCollectionWriter.collection().idList(idList)
            .collectionPredicate(collectionPredicate).resourceTargetMap(resourceTargetMap).build();

    final String collection = collectionWriter.render();

    final String serviceURI = listServiceBaseURI + listURI;
    final ServiceNodeWriter serviceNodeWriter;
    serviceNodeWriter = ServiceNodeWriter.init().serviceURI(serviceURI).servicePredicate(IIIFPredicates.SERVICE)
            .serviceType("http://localhost:3000/listcontext.json").build();
    final String serviceNode = serviceNodeWriter.render();

    final MetadataTemplate metadataTemplate;
    final List<ListScope.Prefix> prefixes = Arrays.asList(new ListScope.Prefix(FedoraPrefixes.RDFS),
            new ListScope.Prefix(FedoraPrefixes.MODE), new ListScope.Prefix(IIIFPrefixes.SVCS),
            new ListScope.Prefix(IIIFPrefixes.SC));

    final ListScope scope = new ListScope().fedoraPrefixes(prefixes).sequenceGraph(collection)
            .serviceNode(serviceNode);

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

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

From source file:com.cognifide.aet.job.common.datafilters.removenodes.RemoveNodesDataModifier.java

private Document getDocument(String source, DocumentBuilderFactory dbf) throws ProcessingException {
    try {/*from   w  w  w. j  a  v a2  s .c o  m*/
        DocumentBuilder db = dbf.newDocumentBuilder();
        return db.parse(IOUtils.toInputStream(source, "UTF-8"));
    } catch (IOException | ParserConfigurationException | SAXException e) {
        throw new ProcessingException(e.getMessage(), e);
    }
}

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

@Test(expected = SubversionException.class)
public void test00_noParents() throws Exception {
    Assert.assertFalse(prefix + " does already exist", repository.exists(prefix, Revision.HEAD));
    final Resource resource = prefix.append(Resource.create("no_parents.txt"));

    final Transaction transaction = repository.createTransaction();
    try {/*from  w ww  .  j ava2s  . co m*/
        Assert.assertTrue("transaction must be active", transaction.isActive());
        repository.add(transaction, resource, false, IOUtils.toInputStream("test", AbstractHelper.UTF8));
        Assert.fail("must not complete");
    } finally {
        repository.rollbackIfNotCommitted(transaction);
    }
}

From source file:com.quinsoft.zeidon.standardoe.ActivateOiFromRestServer.java

@Override
public View activate() {
    LodDef lodDef = view.getLodDef();/*from   www .  j  av a2 s  .co m*/
    Application application = lodDef.getApplication();
    String stringResponse = null;
    BufferedBinaryStreamReader reader = null;
    HttpClient client = null;

    try {
        String url = String.format("%s/activate?application=%s&lodDefName=%s", serverUrl, application.getName(),
                view.getLodDef().getName());
        client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        View qual = activateOptions.getQualificationObject();
        String qualStr = qual.serializeOi().asJson().withIncremental().toStringWriter().toString();
        StringEntity entity = new StringEntity(qualStr);
        post.setEntity(entity);
        post.setHeader("Content-Type", "application/json");

        HttpResponse response = client.execute(post);
        InputStream stream = response.getEntity().getContent();
        StatusLine status = response.getStatusLine();
        task.log().info("Status from http activate = %s", status);
        int statusCode = status.getStatusCode();

        // If we're in debug mode, print out the results.
        if (task.log().isDebugEnabled() || statusCode != 200) {
            StringWriter writer = new StringWriter();
            IOUtils.copy(stream, writer, "UTF-8");
            stringResponse = writer.toString();
            task.log().debug("REST response: %s", stringResponse);
            stream = IOUtils.toInputStream(stringResponse, "UTF-8");
        }

        if (statusCode != 200) {
            throw new ZeidonException("http activate failed with status %s", status)
                    .appendMessage("web URL = %s", url);
        }

        List<View> views = getTask().deserializeOi().asJson().fromInputStream(stream).activate();
        View restRc = views.get(0);
        restRc.logObjectInstance();
        Integer rc = restRc.cursor("RestResponse").getAttribute("ReturnCode").getInteger();
        if (rc != 0) {
            String errorMsg = restRc.cursor("RestResponse").getAttribute("ErrorMessage").getString();
            throw new ZeidonRestException("Error activating OI from REST server %d", rc).appendMessage("%s",
                    errorMsg);
        }

        return views.get(1);
    } catch (Exception e) {
        throw ZeidonException.wrapException(e).appendMessage("Server URL = %s", serverUrl);
    } finally {
        IOUtils.closeQuietly(reader);
    }
}

From source file:com.joyent.manta.http.EncryptedHttpHelperTest.java

/**
 * Builds a fully mocked {@link EncryptionHttpHelper} that is setup to
 * be configured for one cipher/mode and executes requests in another
 * cipher/mode.//from   w w  w .j  av a  2 s  .co  m
 */
private static EncryptionHttpHelper fakeEncryptionHttpHelper(String path) throws Exception {
    MantaConnectionContext connectionContext = mock(MantaConnectionContext.class);

    StandardConfigContext config = new StandardConfigContext();

    SupportedCipherDetails cipherDetails = AesCbcCipherDetails.INSTANCE_192_BIT;

    config.setClientEncryptionEnabled(true)
            .setEncryptionPrivateKeyBytes(SecretKeyUtils.generate(cipherDetails).getEncoded())
            .setEncryptionAlgorithm(cipherDetails.getCipherId());

    EncryptionHttpHelper httpHelper = new EncryptionHttpHelper(connectionContext,
            new MantaHttpRequestFactory(UnitTestConstants.UNIT_TEST_URL), config);

    URI uri = URI.create(DEFAULT_MANTA_URL + "/" + path);

    CloseableHttpResponse fakeResponse = mock(CloseableHttpResponse.class);
    StatusLine statusLine = new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, "OK");

    SupportedCipherDetails objectCipherDetails = AesGcmCipherDetails.INSTANCE_128_BIT;

    Header[] headers = new Header[] {
            // Notice this is a different cipher than the one set in config
            new BasicHeader(MantaHttpHeaders.ENCRYPTION_CIPHER, objectCipherDetails.getCipherId()) };

    when(fakeResponse.getAllHeaders()).thenReturn(headers);
    when(fakeResponse.getStatusLine()).thenReturn(statusLine);

    BasicHttpEntity fakeEntity = new BasicHttpEntity();
    InputStream source = IOUtils.toInputStream("I'm a stream", StandardCharsets.US_ASCII);
    EofSensorInputStream stream = new EofSensorInputStream(source, null);
    fakeEntity.setContent(stream);
    when(fakeResponse.getEntity()).thenReturn(fakeEntity);

    when(connectionContext.getHttpClient()).thenReturn(new FakeCloseableHttpClient(fakeResponse));

    return httpHelper;
}

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

/**
 * Using search results XML as input, compose a JavaScript array that contains
 * the data necessary to render the search results in a Google Maps script
 * that uses the Marker Clusterer component.
 * //from   w ww .  j  a  v a2  s.c o m
 * @param    xml  search resuts XML string
 * @return   a string representation of the JavaScript array
 */
public String parseResultSet(String xml) {
    String jsArray = "";
    StringBuilder jsArrayBuilder = new StringBuilder("[\n");

    if (xml != null) {
        InputStream inputStream = null;
        try {
            inputStream = IOUtils.toInputStream(xml, "UTF-8");
            DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
            CachedXPathAPI xpathapi = new CachedXPathAPI();

            Document document = null;
            document = documentBuilder.parse(inputStream);

            if (document != null) {
                Node numFoundNode = null;
                numFoundNode = xpathapi.selectSingleNode(document, "//resultset/@numFound");
                if (numFoundNode != null) {
                    String numFoundStr = numFoundNode.getNodeValue();
                    this.numFound = new Integer(numFoundStr);
                }

                NodeList dataPackageNodeList = xpathapi.selectNodeList(document, "//resultset/document");

                if (dataPackageNodeList != null) {
                    Set<String> coordinatesSet = new TreeSet<String>();
                    for (int i = 0; i < dataPackageNodeList.getLength(); i++) {
                        Node dataPackageNode = dataPackageNodeList.item(i);

                        String packageIdField = null;
                        String titleField = null;
                        String titleLinkField = null;
                        String pubDateField = null;
                        String locationField = null;

                        NodeList coordinatesNodeList = xpathapi.selectNodeList(dataPackageNode,
                                COORDINATES_PATH);

                        /*
                         * If we can't determine the coordinates, we can't map the
                         * data package, so just continue to the next data package
                         */
                        if (coordinatesNodeList != null) {
                            if (coordinatesNodeList.getLength() > 0) {
                                for (int j = 0; j < coordinatesNodeList.getLength(); j++) {
                                    if (j == 1)
                                        break;
                                    Node coordinatesNode = coordinatesNodeList.item(j);
                                    String coordinates = coordinatesNode.getTextContent();
                                    boolean useOffset = false;
                                    locationField = composeLocationField(coordinates, coordinatesSet,
                                            useOffset);
                                    if (locationField == null) {
                                        continue;
                                    } else {
                                        coordinatesSet.add(locationField);
                                    }
                                }
                            } else {
                                continue;
                            }
                        } else {
                            continue;
                        }

                        String packageId = null;
                        Node packageIdNode = xpathapi.selectSingleNode(dataPackageNode, PACKAGEID_PATH);
                        if (packageIdNode != null) {
                            packageId = packageIdNode.getTextContent();
                            packageIdField = composePackageIdField(packageId);
                        }

                        Node titleNode = xpathapi.selectSingleNode(dataPackageNode, TITLE_PATH);
                        if (titleNode != null) {
                            String title = titleNode.getTextContent();
                            titleField = composeTitleField(title);
                            if (packageId != null) {
                                titleLinkField = composeTitleLinkField(title, packageId);
                            }
                        }

                        Node pubDateNode = xpathapi.selectSingleNode(dataPackageNode, PUBDATE_PATH);
                        if (pubDateNode != null) {
                            String pubDate = pubDateNode.getTextContent();
                            pubDateField = composePubDateField(pubDate);
                        }

                        String jsArrayElement = composeArrayElement(packageIdField, titleField, titleLinkField,
                                pubDateField, locationField);
                        jsArrayBuilder.append(jsArrayElement);
                    }
                }
            }
        } catch (Exception e) {
            logger.error("Error parsing search result set: " + e.getMessage());
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    ;
                }
            }
        }
    }

    jsArrayBuilder.append("];\n");
    jsArray = jsArrayBuilder.toString();

    return jsArray;
}