List of usage examples for org.apache.commons.io IOUtils toInputStream
public static InputStream toInputStream(String input, String encoding) throws IOException
From source file:mitm.common.cache.ContentCacheImplTest.java
@Test public void testRemoveEntry() throws IOException, CacheException { FileStreamCacheEntry entry = new FileStreamCacheEntry("body"); assertFalse(entry.isValid());/*from ww w . j a v a 2 s. c om*/ assertNull(entry.getFile(false)); String content = "Some content"; entry.store(IOUtils.toInputStream(content, "UTF-8")); assertTrue(entry.isValid()); String key = "key"; cache.addEntry(key, entry); entry = new FileStreamCacheEntry("other body"); content = "Other content"; entry.store(IOUtils.toInputStream(content, "UTF-8")); cache.addEntry(key, entry); List<CacheEntry> entries = cache.getAllEntries(key); assertEquals(2, entries.size()); entry = (FileStreamCacheEntry) entries.get(0); assertEquals("body", entry.getId()); File file = entry.getFile(false); assertTrue(file.exists()); cache.removeEntry(key, "body"); assertFalse(file.exists()); entries = cache.getAllEntries(key); assertEquals(1, entries.size()); entry = (FileStreamCacheEntry) entries.get(0); assertEquals("other body", entry.getId()); assertEquals(null, entry.getObject()); assertTrue(entry.getFile(false).exists()); }
From source file:edu.lternet.pasta.client.ResultSetUtility.java
private void parseResultSet(String xml) { if (xml != null) { InputStream inputStream = null; try {/*from w ww. ja v a 2 s .c o m*/ 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); } Node startNode = null; startNode = xpathapi.selectSingleNode(document, "//resultset/@start"); if (startNode != null) { String startStr = startNode.getNodeValue(); this.start = new Integer(startStr); } } } catch (Exception e) { logger.error("Error parsing search result set: " + e.getMessage()); } finally { if (inputStream != null) { try { inputStream.close(); } catch (IOException e) { ; } } } } }
From source file:au.com.redboxresearchdata.fascinator.harvester.GenericJsonHarvester.java
/** * Merge the newly processed data with an (possible) existing data already * present, also convert the completed JSON merge into a Stream for storage. * //from w w w .jav a 2 s . c o m * This implementation just saves the data (except the owner property) to the main payload, ignoring prefix and metadata that came along the original harvest message. * * @param dataJson * an instantiated JSON object containing data to store * @param metaJson * an instantiated JSON object containing metadata to store * @param existing * an instantiated JsonSimple object with any existing data * @throws IOException * if any character encoding issues effect the Stream */ protected InputStream streamMergedJson(JsonObject dataJson, JsonObject metaJson, JsonSimple existing, String idPrefix) throws IOException { existing.getJsonObject().putAll(dataJson); // remove the owner from the main payload existing.getJsonObject().remove("owner"); // Turn into a stream to return String jsonString = existing.toString(true); return IOUtils.toInputStream(jsonString, "UTF-8"); }
From source file:edu.lternet.pasta.client.ReservationsManager.java
/** * Return the number of subscriptions for a given user. * /*from ww w . ja v a 2 s. c om*/ * @return the number of subscriptions for this user. */ public int numberOfReservations() throws Exception { int numberOfReservations = 0; if (this.uid != null && !this.uid.equals("public")) { String xmlString = listActiveReservations(); DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance(); try { DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder(); InputStream inputStream = IOUtils.toInputStream(xmlString, "UTF-8"); Document document = documentBuilder.parse(inputStream); Element documentElement = document.getDocumentElement(); NodeList reservations = documentElement.getElementsByTagName("reservation"); int nReservations = reservations.getLength(); for (int i = 0; i < nReservations; i++) { Node reservationNode = reservations.item(i); NodeList reservationChildren = reservationNode.getChildNodes(); String principal = ""; for (int j = 0; j < reservationChildren.getLength(); j++) { Node childNode = reservationChildren.item(j); if (childNode instanceof Element) { Element reservationElement = (Element) childNode; if (reservationElement.getTagName().equals("principal")) { Text text = (Text) reservationElement.getFirstChild(); if (text != null) { principal = text.getData().trim(); if (principal.startsWith(this.uid)) { numberOfReservations++; } } } } } } } catch (Exception e) { logger.error("Exception:\n" + e.getMessage()); e.printStackTrace(); throw new PastaEventException(e.getMessage()); } } return numberOfReservations; }
From source file:mitm.common.security.ca.CSVRequestConverterTest.java
@Test public void testEmptyLine() throws Exception { String input = "email, organisation, COMMONNAME, firstname, lastname\r\n" + "test1@example.com,org, cn1 , firstname1, lastname1\r\n\r\n" + "test2@example.com,org2,cn2,firstname2,lastname2"; CSVRequestConverter converter = new CSVRequestConverter(); List<RequestParameters> parameters = converter .convertCSV(IOUtils.toInputStream(input, CharacterEncoding.US_ASCII)); assertNotNull(parameters);//from ww w.ja v a 2 s . c om assertEquals(2, parameters.size()); RequestParameters request = parameters.get(0); assertEquals("test1@example.com", request.getEmail()); assertEquals("EMAILADDRESS=test1@example.com, GIVENNAME=firstname1, SURNAME=lastname1, CN=cn1, O=org", request.getSubject().toString()); request = parameters.get(1); assertEquals("test2@example.com", request.getEmail()); assertEquals("EMAILADDRESS=test2@example.com, GIVENNAME=firstname2, SURNAME=lastname2, CN=cn2, O=org2", request.getSubject().toString()); }
From source file:com.intuit.karate.cucumber.FeatureWrapper.java
private FeatureWrapper(String text, ScriptEnv scriptEnv) { this.text = text; this.scriptEnv = scriptEnv; this.feature = CucumberUtils.parse(text); try {/*w w w .j a va 2 s. c om*/ InputStream is = IOUtils.toInputStream(text, "utf-8"); this.lines = IOUtils.readLines(is, "utf-8"); } catch (Exception e) { throw new RuntimeException(e); } featureSections = new ArrayList<>(); List<CucumberTagStatement> elements = feature.getFeatureElements(); int count = elements.size(); for (int i = 0; i < count; i++) { CucumberTagStatement cts = elements.get(i); if (cts instanceof CucumberScenario) { CucumberScenario sw = (CucumberScenario) cts; ScenarioWrapper scenario = new ScenarioWrapper(this, -1, sw, null); FeatureSection section = new FeatureSection(i, this, scenario, null); featureSections.add(section); } else if (cts instanceof CucumberScenarioOutline) { CucumberScenarioOutline cso = (CucumberScenarioOutline) cts; ScenarioOutlineWrapper scenarioOutline = new ScenarioOutlineWrapper(this, cso); FeatureSection section = new FeatureSection(i, this, null, scenarioOutline); featureSections.add(section); } else { throw new RuntimeException("unexpected type: " + cts.getClass()); } } }
From source file:com.thruzero.domain.dsc.dao.DscTextEnvelopeDAO.java
/** * Use {@link com.thruzero.domain.locator.DAOLocator DAOLocator} to access a particular DAO. *///from ww w .j ava 2 s . co m private DscTextEnvelopeDAO() { super(new DomainObjectTransformer<TextEnvelope>() { @Override public TextEnvelope resurrect(EntityPath primaryKey, DataStoreEntity data) { byte[] dataAsBytes; InputStream is = data.getData(); try { dataAsBytes = IOUtils.toByteArray(is); } catch (IOException e) { throw new DAOException("ERROR: Can't read input stream (to byte array)."); } finally { IOUtils.closeQuietly(is); } TextEnvelope result = new TextEnvelope(primaryKey, new String(dataAsBytes)); return result; } @Override public DataStoreEntity flatten(TextEnvelope domainObject) { String data = domainObject.getData(); try { return new SimpleDataStoreEntity(IOUtils.toInputStream(data, CharEncoding.UTF_8), domainObject.getEntityPath()); } catch (IOException e) { throw new RuntimeException("couldn't convert data to InputStream.", e); } } }); }
From source file:com.hortonworks.registries.storage.filestorage.DbFileStorageTest.java
@Test public void testDelete() throws Exception { try {/*from w ww . j a v a 2 s . 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); Assert.assertTrue(dbFileStorage.exists(FILE_NAME)); dbFileStorage.delete(FILE_NAME); Assert.assertFalse(dbFileStorage.exists(FILE_NAME)); try { dbFileStorage.download(FILE_NAME); Assert.fail("Expected IOException in download after delete"); } catch (IOException ex) { } transactionManager.commitTransaction(); } catch (Exception e) { transactionManager.rollbackTransaction(); throw e; } }
From source file:ch.entwine.weblounge.common.impl.content.image.LazyImageResourceImpl.java
/** * Loads the complete image.//from w w w . j a v a2s . com */ protected void loadImage() { try { // Get a hold of the image reader ImageResourceReader reader = (readerRef != null) ? readerRef.get() : null; if (reader == null) { reader = new ImageResourceReader(); // No need to keep the reference, since we're done after this } // Load the image image = reader.read(IOUtils.toInputStream(imageXml, "utf-8"), uri.getSite()); isHeaderLoaded = true; isBodyLoaded = true; cleanupAfterLoading(); } catch (Throwable e) { logger.error("Failed to lazy-load body of {}", uri); throw new IllegalStateException("Failed to lazy-load body of " + uri, e); } }
From source file:de.shadowhunt.subversion.internal.AbstractRepositoryAddIT.java
@Test(expected = SubversionException.class) public void test00_rollback() throws Exception { final Resource resource = prefix.append(Resource.create("rollback.txt")); final Transaction transaction = repository.createTransaction(); try {/* w w w . j a v a2 s. co m*/ Assert.assertTrue("transaction must be active", transaction.isActive()); repository.add(transaction, resource, false, IOUtils.toInputStream("test", AbstractHelper.UTF8)); Assert.assertTrue("transaction must be active", transaction.isActive()); Assert.assertEquals("change set must contain: " + resource, Status.ADDED, transaction.getChangeSet().get(resource)); repository.rollback(transaction); Assert.assertFalse("transaction must not be active", transaction.isActive()); } finally { repository.rollbackIfNotCommitted(transaction); } }