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:ch.entwine.weblounge.common.impl.content.page.LazyPageImpl.java

/**
 * Loads the page header only./*w w w  .j  a  v a2s  .c  o  m*/
 */
protected void loadPageHeader() {
    try {

        // Get a hold of the page reader
        PageReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new PageReader();
            readerRef = new WeakReference<PageReader>(reader);
        }

        // If no separate header was given, then we need to load the whole thing
        // instead.
        if (headerXml == null) {
            loadPage();
            return;
        }

        // Load the page header
        page = reader.readHeader(IOUtils.toInputStream(headerXml, "utf-8"), uri.getSite());
        isHeaderLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else
            headerXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load header of {}", uri);
        throw new IllegalStateException(e);
    }
}

From source file:ch.entwine.weblounge.contentrepository.impl.PageSerializer.java

/**
 * {@inheritDoc}/*  ww w . j a  va 2  s .c o  m*/
 * 
 * @see ch.entwine.weblounge.common.repository.ResourceSerializer#toResource(ch.entwine.weblounge.common.site.Site,
 *      java.util.List)
 */
public Resource<?> toResource(Site site, List<ResourceMetadata<?>> metadata) {
    for (ResourceMetadata<?> metadataItem : metadata) {
        if (XML.equals(metadataItem.getName())) {
            String resourceXml = (String) metadataItem.getValues().get(0);
            try {
                ResourceReader<ResourceContent, Page> reader = getReader();
                Page page = reader.read(IOUtils.toInputStream(resourceXml, "UTF-8"), site);
                return page;
            } catch (SAXException e) {
                logger.warn("Error parsing page from metadata", e);
                return null;
            } catch (IOException e) {
                logger.warn("Error parsing page from metadata", e);
                return null;
            } catch (ParserConfigurationException e) {
                logger.warn("Error parsing page from metadata", e);
                return null;
            }
        }
    }
    return null;
}

From source file:ddf.catalog.transformer.queryresponse.geojson.GeoJsonQueryResponseTransformerTest.java

private MetacardTransformer createCustomMetacardTransformer(String binContent) {
    return (metacard,
            arguments) -> new BinaryContentImpl(IOUtils.toInputStream(binContent, StandardCharsets.UTF_8));
}

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

@Test
public void test01_ModifyMultipleLockedFiles() throws Exception {
    final String content = "test";
    final Resource resourceA = prefix.append(Resource.create("lockedFileA.txt"));
    final Resource resourceB = prefix.append(Resource.create("lockedFileB.txt"));

    AbstractRepositoryAddIT.file(repository, resourceA, "A", true);
    AbstractRepositoryAddIT.file(repository, resourceB, "B", true);

    repository.lock(resourceA, false);/*from   w w w. j  a v  a2 s .  c o  m*/
    repository.lock(resourceB, false);

    final Transaction transaction = repository.createTransaction();
    try {
        repository.add(transaction, resourceA, true, IOUtils.toInputStream(content, AbstractHelper.UTF8));
        repository.add(transaction, resourceB, true, IOUtils.toInputStream(content, AbstractHelper.UTF8));
        repository.commit(transaction, "add " + resourceA + " " + resourceB);
    } finally {
        repository.rollbackIfNotCommitted(transaction);
    }

    final InputStream expectedA = IOUtils.toInputStream(content, AbstractHelper.UTF8);
    final InputStream actualA = repository.download(resourceA, Revision.HEAD);
    AbstractRepositoryDownloadIT.assertEquals("content must match", expectedA, actualA);

    final InputStream expectedB = IOUtils.toInputStream(content, AbstractHelper.UTF8);
    final InputStream actualB = repository.download(resourceB, Revision.HEAD);
    AbstractRepositoryDownloadIT.assertEquals("content must match", expectedB, actualB);
}

From source file:io.redlink.sdk.analysis.AnalysisRequest.java

/**
 * Get current request content as {@link InputStream}
 *
 * @return {@link InputStream} containing the content that is going to be analyzed
 *//*from   w  ww.  j  a va  2  s  .c  o  m*/
public InputStream getContent() {
    switch (contentType) {
    case EMPTY:
        throw new RuntimeException("There is not Content available to analyze");
    case FILE:
        if (consumed)
            try {
                contentStream = Optional.of((InputStream) new FileInputStream(contentFile.get()));
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e);
            }
        break;
    case STRING:
        if (consumed) {
            if (contentEncoding.isPresent()) {
                try {
                    contentStream = Optional
                            .of(IOUtils.toInputStream(contentString.get(), contentEncoding.get()));
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            } else {
                contentStream = Optional.of(IOUtils.toInputStream(contentString.get()));
            }
        }
        break;
    case INPUTSTREAM:
        if (consumed) {
            throw new RuntimeException("The Content Stream to be analyzed has been already consumed");
        }
        break;
    default:
        break;
    }

    consumed = true;
    return contentStream.get();
}

From source file:ch.entwine.weblounge.common.impl.content.image.LazyImageResourceImpl.java

/**
 * Loads the image body only./*ww w.j  a v  a  2  s  . c  om*/
 */
protected void loadImageBody() {
    try {

        // Get a hold of the image reader
        ImageResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new ImageResourceReader();
            readerRef = new WeakReference<ImageResourceReader>(reader);
        }

        // Load the image body
        image = reader.readBody(IOUtils.toInputStream(imageXml, "utf-8"), uri.getSite());
        isBodyLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else if (headerXml != null)
            imageXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load body of {}: {}", uri, e.getMessage());
        throw new IllegalStateException(e);
    }
}

From source file:ch.entwine.weblounge.common.impl.content.file.LazyFileResourceImpl.java

/**
 * Loads the file body only./*w w w .  j  a  v  a2 s  . c o m*/
 */
protected void loadFileBody() {
    try {

        // Get a hold of the file reader
        FileResourceReader reader = (readerRef != null) ? readerRef.get() : null;
        if (reader == null) {
            reader = new FileResourceReader();
            readerRef = new WeakReference<FileResourceReader>(reader);
        }

        // Load the file body
        file = reader.readBody(IOUtils.toInputStream(fileXml, "utf-8"), uri.getSite());
        isBodyLoaded = true;
        if (isHeaderLoaded && isBodyLoaded)
            cleanupAfterLoading();
        else if (headerXml != null)
            fileXml = null;

    } catch (Throwable e) {
        logger.error("Failed to lazy-load body of {}: {}", uri, e.getMessage());
        throw new IllegalStateException(e);
    }
}

From source file:com.github.restdriver.serverdriver.http.DefaultResponseTest.java

@Test
public void noContentEncodingOnResponseIsTreatedAsUTF8() throws Exception {
    HttpEntity mockEntity = mock(HttpEntity.class);
    when(mockEntity.getContentEncoding()).thenReturn(null);
    when(mockEntity.getContent()).thenReturn(IOUtils.toInputStream("????", "UTF-8"));

    Header[] mockedHeaders = new Header[0];

    HttpResponse mockResponse = mock(HttpResponse.class);
    setMockStatusCode(mockResponse, 200);
    when(mockResponse.getAllHeaders()).thenReturn(mockedHeaders);
    when(mockResponse.getEntity()).thenReturn(mockEntity);

    Response response = new DefaultResponse(mockResponse, 12345);

    assertThat(response.getContent(), is("????"));
}

From source file:au.edu.usq.fascinator.transformer.marc.MarcAuthorsTransformer.java

private void createAuthorRecord(DigitalObject object, String id, String title, String author)
        throws TransformerException {
    try {//from w w  w  .  j av  a 2 s  .co  m
        // Generate OID using author name + title
        String oid = DigestUtils.md5Hex(author + "#" + title);
        log.debug("Creating author record: {} ({})", author, oid);

        // Signal a reharvest on the author object to index them
        DigitalObject authorObj = StorageUtils.getDigitalObject(storage, oid);

        // Add an author metadata payload to the current object
        JsonConfigHelper authorJson = new JsonConfigHelper();
        authorJson.set("id", id);
        authorJson.set("author", author);
        authorJson.set("title", title);
        StorageUtils.createOrUpdatePayload(authorObj, AUTHOR_PAYLOAD,
                IOUtils.toInputStream(authorJson.toString(), "UTF-8"));

        // Generate the object properties
        Properties objectMeta = object.getMetadata();
        Properties authorObjMeta = authorObj.getMetadata();
        copyProperty(objectMeta, authorObjMeta, "metaPid");
        copyProperty(objectMeta, authorObjMeta, "rulesOid");
        copyProperty(objectMeta, authorObjMeta, "repository.name");
        copyProperty(objectMeta, authorObjMeta, "repository.type");
        authorObjMeta.setProperty("jsonConfigOid", oid);
        authorObjMeta.setProperty("id", id);
        authorObjMeta.setProperty("title", title);
        authorObjMeta.setProperty("author", author);
        authorObjMeta.setProperty("recordType", "marc-author");
        authorObj.close();

        harvestClient.reharvest(oid);
    } catch (Exception e) {
        e.printStackTrace();
        throw new TransformerException(e);
    }
}

From source file:edu.gmu.csiss.automation.pacs.utils.BaseTool.java

/**
  * Convert string to input stream/*from  ww w  . j av a  2s . co m*/
  * @param str
  * @return
  * @throws IOException 
  */
public InputStream convertString2InputStream(String str) throws IOException {
    InputStream stream = IOUtils.toInputStream(str, "UTF-8");
    return stream;
}