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.cyberduck.core.googledrive.DriveReadFeature.java

@Override
public InputStream read(final Path file, final TransferStatus status, final ConnectionCallback callback)
        throws BackgroundException {
    try {/* w  w w.java2  s.c om*/
        if (file.getType().contains(Path.Type.placeholder)) {
            final DescriptiveUrl link = new DriveUrlProvider().toUrl(file).find(DescriptiveUrl.Type.http);
            if (DescriptiveUrl.EMPTY.equals(link)) {
                log.warn(String.format("Missing web link for file %s", file));
                return new NullInputStream(file.attributes().getSize());
            }
            // Write web link file
            return IOUtils.toInputStream(UrlFileWriterFactory.get().write(link), Charset.defaultCharset());
        } else {
            final String base = session.getClient().getRootUrl();
            final HttpUriRequest request = new HttpGet(String.format(
                    String.format("%%s/drive/v3/files/%%s?alt=media&supportsTeamDrives=%s",
                            PreferencesFactory.get().getBoolean("googledrive.teamdrive.enable")),
                    base,
                    new DriveFileidProvider(session).getFileid(file, new DisabledListProgressListener())));
            request.addHeader(HTTP.CONTENT_TYPE, MEDIA_TYPE);
            if (status.isAppend()) {
                final HttpRange range = HttpRange.withStatus(status);
                final String header;
                if (-1 == range.getEnd()) {
                    header = String.format("bytes=%d-", range.getStart());
                } else {
                    header = String.format("bytes=%d-%d", range.getStart(), range.getEnd());
                }
                if (log.isDebugEnabled()) {
                    log.debug(String.format("Add range header %s for file %s", header, file));
                }
                request.addHeader(new BasicHeader(HttpHeaders.RANGE, header));
                // Disable compression
                request.addHeader(new BasicHeader(HttpHeaders.ACCEPT_ENCODING, "identity"));
            }
            final HttpClient client = session.getHttpClient();
            final HttpResponse response = client.execute(request);
            switch (response.getStatusLine().getStatusCode()) {
            case HttpStatus.SC_OK:
            case HttpStatus.SC_PARTIAL_CONTENT:
                return new HttpMethodReleaseInputStream(response);
            default:
                throw new DriveExceptionMappingService().map(new HttpResponseException(
                        response.getStatusLine().getStatusCode(), response.getStatusLine().getReasonPhrase()));
            }
        }
    } catch (IOException e) {
        throw new DriveExceptionMappingService().map("Download {0} failed", e, file);
    }
}

From source file:com.eviware.soapui.support.SoapUIVersionUpdate.java

public void getLatestVersionAvailable(String documentContent) throws Exception {
    try {/*from  w  w  w. ja v a 2s.c  o m*/
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        DocumentBuilder db = dbf.newDocumentBuilder();

        InputStream inputStream = IOUtils.toInputStream(documentContent, "UTF-8");

        Document doc = db.parse(inputStream);
        doc.getDocumentElement().normalize();
        NodeList nodeList = doc.getElementsByTagName("version");

        Node firstNode = nodeList.item(0);

        if (firstNode.getNodeType() == Node.ELEMENT_NODE) {

            Element firstElement = (Element) firstNode;

            latestVersion = getNodeValue(firstElement, "version-number");
            releaseNotesCore = getNodeValue(firstElement, "release-notes-core");
            releaseNotesPro = getNodeValue(firstElement, "release-notes-pro");
            downloadLinkCore = getNodeValue(firstElement, "download-link-core");
            downloadLinkPro = getNodeValue(firstElement, "download-link-pro");
        }
    } catch (Exception e) {
        SoapUI.logError(e, "Network Error for Version Update or Proxy");
        throw e;
    }
}

From source file:com.joyent.manta.client.MantaDirectoryListingIteratorTest.java

public void allowsSkippingFirstResult() throws Exception {
    String dirListing = "{\"name\":\".joyent\",\"type\":\"directory\",\"mtime\":\"2015-04-16T22:50:11.353Z\"}\n"
            + "{\"name\":\"foo\",\"etag\":\"2968452a-9f78-edbe-a5fa-fe167963f4cf\",\"type\":\"object\",\"contentType\":\"text/plain\",\"contentMD5\":\"1B2M2Y8AsgTpgAmY7PhCfg==\",\"mtime\":\"2017-04-16T23:20:12.393Z\"}";
    final Header contentTypeHeader = new BasicHeader(CONTENT_TYPE,
            MantaObjectResponse.DIRECTORY_RESPONSE_CONTENT_TYPE);
    when(responseEntity.getContentType()).thenReturn(contentTypeHeader);
    when(response.getAllHeaders()).thenReturn(new Header[] { contentTypeHeader });
    when(responseEntity.getContent()).thenReturn(IOUtils.toInputStream(dirListing, StandardCharsets.UTF_8));

    final MantaDirectoryListingIterator itr = new MantaDirectoryListingIterator("/usr/stor/dir", httpHelper,
            MAX_RESULTS);//w  ww  . j a  va2  s  . c o m

    itr.next();
    Map<String, Object> secondResult = itr.next();

    Assert.assertEquals(secondResult.get("name"), "foo");
    Assert.assertEquals(secondResult.get("etag"), "2968452a-9f78-edbe-a5fa-fe167963f4cf");
    Assert.assertEquals(secondResult.get("type"), "object");
    Assert.assertEquals(secondResult.get("contentType"), "text/plain");
    Assert.assertEquals(secondResult.get("contentMD5"), "1B2M2Y8AsgTpgAmY7PhCfg==");
    Assert.assertEquals(secondResult.get("mtime"), "2017-04-16T23:20:12.393Z");
    Assert.expectThrows(NoSuchElementException.class, itr::next);
}

From source file:com.telefonica.euro_iaas.sdc.puppetwrapper.auth.OpenStackAuthenticationTokenTest.java

@Before
public void setup() throws IOException {

    httpClient = mock(HttpClient.class);
    response = mock(HttpResponse.class);
    statusLine = mock(StatusLine.class);
    httpEntity = mock(HttpEntity.class);
    is = IOUtils.toInputStream(payload, "UTF-8");

    params.add("url");
    params.add("tenant");
    params.add("user");
    params.add("passw");
    params.add(httpClient);//from www . java2  s .  c  om
    params.add(new Long(3));

    openStackAuthenticationToken = new OpenStackAuthenticationToken(params);
}

From source file:com.jkoolcloud.tnt4j.streams.matchers.XPathMatcher.java

/**
 * Evaluates match <tt>expression</tt> against provided <tt>data</tt> using XPath.
 *
 * @param expression//from   ww w  . j  a  va2s  . c o m
 *            XPath expression to check
 * @param data
 *            data {@link String} or {@link org.w3c.dom.Node} to evaluate expression to
 * @return true if expression returns any result
 */
@Override
public boolean evaluate(String expression, Object data) throws Exception {
    Node xmlDoc;
    if (data instanceof Node) {
        xmlDoc = (Node) data;
    } else {
        String xmlString = Utils.toString(data);
        if (StringUtils.isEmpty(xmlString)) {
            return false;
        }
        builderLock.lock();
        try {
            xmlDoc = builder.parse(IOUtils.toInputStream(xmlString, Utils.UTF8));
        } finally {
            builderLock.unlock();
        }
    }
    xPathLock.lock();
    try {
        String expressionResult = xPath.evaluate(expression, xmlDoc);

        if ("true".equalsIgnoreCase(expressionResult) || "false".equalsIgnoreCase(expressionResult)) { // NON-NLS
            return Boolean.parseBoolean(expressionResult);
        }

        return StringUtils.isNotEmpty(expressionResult);
    } finally {
        xPathLock.unlock();
    }
}

From source file:com.thruzero.domain.dsc.ws.WsDataStoreContainer.java

@Override
public DataStoreEntity readEntity(String entityName) {
    MultivaluedMap<String, String> params = new MultivaluedMapImpl();
    params.add("containerPath", resourceContainerPath.getPath());
    params.add("entityName", entityName);

    String response = resource.path("readEntity").queryParams(params).get(String.class);

    SimpleDataStoreEntity result;/*from w ww . j av a2 s.c  om*/
    try {
        result = new SimpleDataStoreEntity(IOUtils.toInputStream(response, CharEncoding.UTF_8),
                new EntityPath(new ContainerPath(), entityName));
        return result;
    } catch (IOException e) {
        throw new RuntimeException("couldn't convert data to InputStream.", e);
    }
}

From source file:mitm.common.fetchmail.FetchmailPropertiesImpl.java

@Override
public FetchmailConfig getFetchmailConfig() throws HierarchicalPropertiesException {
    FetchmailConfig config = null;/*from  w ww  .j av a 2s.  co m*/

    String xml = getFetchmailXMLConfig();

    try {
        if (StringUtils.isNotEmpty(xml)) {
            config = FetchmailConfigFactory.unmarshall(IOUtils.toInputStream(xml, CharEncoding.US_ASCII));
        }
    } catch (JAXBException e) {
        throw new HierarchicalPropertiesException("Error unmarshalling XML.", e);
    } catch (IOException e) {
        throw new HierarchicalPropertiesException("Error reading XML.", e);
    }

    if (config == null) {
        config = new FetchmailConfig();
    }

    return config;
}

From source file:cool.pandora.modeller.ui.handlers.iiif.PatchManifestHandler.java

private static InputStream getManifestMetadata(final URI collectionIdURI, final URI sequenceIdURI,
        final Map<String, BagInfoField> map) {

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

    final String label = getMapValue(map, ManifestPropertiesImpl.FIELD_LABEL);
    final String attribution = getMapValue(map, ManifestPropertiesImpl.FIELD_ATTRIBUTION);
    final String license = getMapValue(map, ManifestPropertiesImpl.FIELD_LICENSE);
    final String rendering = getMapValue(map, ManifestPropertiesImpl.FIELD_RENDERING);
    final String logo = getMapValue(map, ManifestPropertiesImpl.FIELD_INSTITUTION_LOGO_URI);
    final String author = getMapValue(map, ManifestPropertiesImpl.FIELD_AUTHOR);
    final String published = getMapValue(map, ManifestPropertiesImpl.FIELD_PUBLISHED);

    final ManifestScope scope = new ManifestScope().fedoraPrefixes(prefixes)
            .collectionURI(collectionIdURI.toString()).sequenceURI(sequenceIdURI.toString()).label(label)
            .attribution(attribution).license(license).logo(logo).rendering(rendering).author(author)
            .published(published);/*  w  ww  .  j ava  2 s . co  m*/

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

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

From source file:cool.pandora.modeller.ui.handlers.iiif.PatchSequenceHandler.java

private static InputStream getSequenceMetadata(final ArrayList<String> resourceIDList,
        final String collectionPredicate, final URI resourceContainerIRI) {
    final RDFCollectionWriter collectionWriter;
    collectionWriter = RDFCollectionWriter.collection().idList(resourceIDList)
            .collectionPredicate(collectionPredicate).resourceContainerIRI(resourceContainerIRI.toString())
            .build();//from   w  ww . j ava2 s  .  c om

    final String collection = collectionWriter.render();
    final MetadataTemplate metadataTemplate;
    final List<CollectionScope.Prefix> prefixes = Arrays.asList(new CollectionScope.Prefix(FedoraPrefixes.RDFS),
            new CollectionScope.Prefix(FedoraPrefixes.MODE));

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

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

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

From source file:mitm.common.cache.ContentCacheImplTest.java

@Test
public void testAddEntry() throws IOException, CacheException {
    FileStreamCacheEntry entry = new FileStreamCacheEntry("body");

    assertFalse(entry.isValid());//from w  ww .  j  a  v  a  2s  . c o  m

    assertNull(entry.getFile(false));

    entry.setObject("test");

    String content = "Some content";

    entry.store(IOUtils.toInputStream(content, "UTF-8"));

    assertTrue(entry.isValid());

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    entry.writeTo(bos);

    String read = new String(bos.toByteArray(), "UTF-8");

    assertEquals(content, read);

    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());
    assertEquals("test", entry.getObject());
    assertTrue(entry.getFile(false).exists());

    entry = (FileStreamCacheEntry) entries.get(1);
    assertEquals("other body", entry.getId());
    assertEquals(null, entry.getObject());
    assertTrue(entry.getFile(false).exists());
}