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) 

Source Link

Document

Convert the specified string to an input stream, encoded as bytes using the default character encoding of the platform.

Usage

From source file:net.menthor.editor.v2.util.Util.java

public static InputStream convertStringToInputStream(String str) throws IOException {
    return IOUtils.toInputStream(str);
}

From source file:com.msopentech.odatajclient.testservice.utils.JSONUtilities.java

/**
 * {@inheritDoc }//from  w  w w  .j  a  v  a 2s. co  m
 */
@Override
protected InputStream normalizeLinks(final String entitySetName, final String entityKey, final InputStream is,
        final NavigationLinks links) throws Exception {
    final ObjectMapper mapper = new ObjectMapper();
    final ObjectNode srcNode = (ObjectNode) mapper.readTree(is);

    if (links != null) {
        for (String linkTitle : links.getLinkNames()) {
            // normalize link
            srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX);
            srcNode.set(linkTitle + JSON_NAVIGATION_SUFFIX,
                    new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle)));
        }

        for (String linkTitle : links.getInlineNames()) {
            // normalize link if exist; declare a new one if missing
            srcNode.remove(linkTitle + JSON_NAVIGATION_BIND_SUFFIX);
            srcNode.set(linkTitle + JSON_NAVIGATION_SUFFIX,
                    new TextNode(String.format("%s(%s)/%s", entitySetName, entityKey, linkTitle)));

            // remove inline
            srcNode.remove(linkTitle);

            // remove from links
            links.removeLink(linkTitle);
        }
    }

    srcNode.set(JSON_EDITLINK_NAME,
            new TextNode(Constants.DEFAULT_SERVICE_URL + entitySetName + "(" + entityKey + ")"));

    return IOUtils.toInputStream(srcNode.toString());
}

From source file:com.edgenius.wiki.service.impl.ThemeServiceImpl.java

public List<Skin> getAvailableSkins() {
    /*//from  www .j  a  va 2  s.  c o  m
     * Get skin from install zip files list first, then validate if they are explode....
     * I am just not very sure explode mode is good way to implement skin. maybe change to 
     * servlet download theme resource rather than put them into web root directory 
     * However, ... so far, read zip is not quite necessary...
     */
    Map<Long, Skin> skinList = new TreeMap<Long, Skin>(new CompareToComparator<Long>(
            CompareToComparator.TYPE_KEEP_SAME_VALUE | CompareToComparator.DESCEND));
    ArrayList<Skin> skins = new ArrayList<Skin>();
    try {
        if (!skinResourcesRoot.getFile().isDirectory()) {
            log.error("The skin install root is not directory {}, no install skin detected",
                    skinResourcesRoot.getFile().getAbsolutePath());
            return skins;
        }

        File[] files = skinResourcesRoot.getFile()
                .listFiles((FileFilter) new SuffixFileFilter(INSTALL_EXT_NAME));
        String appliedSkin = Global.Skin;
        if (StringUtils.isBlank(appliedSkin)) {
            appliedSkin = Skin.DEFAULT_SKIN;
        }
        for (File zip : files) {
            String skinXML = getMetafile(zip, "skin.xml");
            InputStream sis = IOUtils.toInputStream(skinXML);
            Skin skin = Skin.fromXML(sis);
            IOUtils.closeQuietly(sis);

            if (StringUtils.isBlank(skin.getPreviewImageName())) {
                skin.setPreviewImageName(Skin.DEFAULT_PREVIEW_IMAGE);
            }

            //set initial status
            long factor = zip.lastModified();
            if (appliedSkin.equalsIgnoreCase(skin.getName())) {
                factor = Long.MAX_VALUE; //always first. 
                skin.setStatus(Skin.STATUS_APPLIED);
                //can not remove applied skin
                skin.setRemovable(false);
            } else {
                skin.setStatus(Skin.STATUS_CANDIDATE);
                skin.setRemovable(true);
                //we also assume user may put default skin zip to install directory
                if (Skin.DEFAULT_SKIN.equalsIgnoreCase(skin.getName())) {
                    //can not remove default skin
                    skin.setRemovable(false);
                }

            }

            //put into list
            skinList.put(factor, skin);
        }

        skins = new ArrayList<Skin>(skinList.values());

        //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        // Append default skin and  Decide Skin.STATUS_DEPLOYED
        if (!skinExplosionRoot.getFile().isDirectory()) {
            log.error("The skin explosion root is not directory {}, no deployed skin detected",
                    skinExplosionRoot.getFile().getAbsolutePath());
        } else {
            File[] deployDirs = skinExplosionRoot.getFile()
                    .listFiles((FileFilter) DirectoryFileFilter.INSTANCE);
            for (File dir : deployDirs) {
                File file = getSkinXML(dir);

                if (!file.exists()) {
                    log.warn("Unable to find skin.xml on skin directory {}", dir.getAbsolutePath());
                    continue;
                }

                //Load the default value of this skin from file system
                FileInputStream is = null;
                try {
                    is = new FileInputStream(file);
                    Skin skin = Skin.fromXML(is);
                    if (skin != null) {
                        int idx = skins.indexOf(skin);
                        if (idx != -1) {
                            skin = skins.get(idx);
                            if (skin.getStatus() < Skin.STATUS_APPLIED) {
                                skin.setStatus(Skin.STATUS_DEPLOYED);
                            }
                        } else {
                            //No zipped default skin in install directory, so insert it to return list.
                            if (Skin.DEFAULT_SKIN.equalsIgnoreCase(skin.getName())) {
                                //can not remove default skin
                                int ins; // if it is applied, always first, otherwise, second
                                skin.setRemovable(false);
                                if (appliedSkin.equalsIgnoreCase(skin.getName())) {
                                    ins = 0;
                                    skin.setStatus(Skin.STATUS_APPLIED);
                                } else {
                                    ins = skins.size() > 0 ? 1 : 0;
                                    skin.setStatus(Skin.STATUS_DEPLOYED);
                                }
                                //insert default skin
                                skins.add(ins, skin);
                            }
                        }
                    }
                } catch (Exception e) {
                    log.error("Failed load skin " + file.getAbsolutePath(), e);
                } finally {
                    IOUtils.closeQuietly(is);
                }
            }

            for (Iterator<Skin> iter = skins.iterator(); iter.hasNext();) {
                Skin skin = iter.next();
                if (skin.getStatus() == Skin.STATUS_CANDIDATE) {
                    //remove it from list 
                    iter.remove();
                    log.warn("Skin {} is removed from visible list as it was not deployed.", skin.getName());
                }

            }
        }
    } catch (IOException e) {
        log.error("Unable retrieve skin home directory.", e);
    }

    return skins;
}

From source file:net.di2e.ecdr.source.rest.CDRAbstractSourceTest.java

@Test(expected = UnsupportedQueryException.class)
public void testBadQueryResponse() throws Exception {
    CDROpenSearchSource source = configureSource();
    QueryRequest request = new QueryRequestImpl(new QueryImpl(CQL.toFilter("id = '12345678910'")));
    when(client.getCurrentURI()).thenReturn(new URI(SERVICE_URL));
    Response webResponse = mock(Response.class);
    when(webResponse.getStatus()).thenReturn(Response.Status.NOT_FOUND.getStatusCode());
    when(webResponse.getEntity()).thenReturn(IOUtils.toInputStream("NOT FOUND"));
    when(client.get()).thenReturn(webResponse);
    source.query(request);/*from  ww w  .j  a v a 2s.c o m*/
    fail("Should have thrown an error during the query.");
}

From source file:info.magnolia.cms.util.ConfigUtil.java

/**
 * Uses a map to find dtds in the resources.
 * @param xml/* ww w . j  a  v a  2s .  co m*/
 * @param dtds
 * @return
 * @throws ParserConfigurationException
 * @throws SAXException
 * @throws IOException
 */
public static Document string2DOM(String xml, final Map<String, String> dtds)
        throws ParserConfigurationException, SAXException, IOException {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setValidating(true);
    DocumentBuilder builder;
    builder = dbf.newDocumentBuilder();
    builder.setEntityResolver(new MapDTDEntityResolver(dtds));
    return builder.parse(IOUtils.toInputStream(xml));
}

From source file:com.comcast.cdn.traffic_control.traffic_router.core.util.PeriodicResourceUpdater.java

boolean filesEqual(final File a, final String newDB) throws IOException {
    if (!a.exists()) {
        return newDB == null;
    }//from   w w w . j a v a  2s. c o  m

    if (newDB == null) {
        return false;
    }

    if (a.length() != newDB.length()) {
        return false;
    }

    try (InputStream newDBStream = IOUtils.toInputStream(newDB)) {
        return fileMd5(a).equals(md5Hex(newDBStream));
    }
}

From source file:com.github.restdriver.clientdriver.unit.ClientDriverResponseTest.java

@Test
public void creatingEmptyResponseHasNullByteArrayWhenFetchingContent() {

    assertThat(new ClientDriverResponse().getContentAsBytes(), is(nullValue()));
    assertThat(new ClientDriverResponse((String) null, null).getContentAsBytes(), is(nullValue()));
    assertThat(new ClientDriverResponse("", null).getContentAsBytes(), is(nullValue()));
    assertThat(new ClientDriverResponse((InputStream) null, null).getContentAsBytes(), is(nullValue()));
    assertThat(new ClientDriverResponse(IOUtils.toInputStream(""), null).getContentAsBytes(), is(nullValue()));

}

From source file:de.thischwa.pmcms.tool.connection.ftp.FtpTransfer.java

/**
 * Uploads a 'file' with the content of the InputStream and the name 'name' to the current dir of FTPClient.
 * If the 'file' exists, it will be deleted before.
 *
 * @throws ConnectionRunningException//www. java 2  s . c o m
 */
private void uploadToCurrentDir(final String name, final InputStream in) throws ConnectionRunningException {
    // TODO implement the server reconnect here!!
    OutputStream serverOut = null;
    try {
        // 1. check, if target file exists and delete it
        FTPFile serverFile = getByName(ftpClient.listFiles(), name);
        if (serverFile != null) {
            if (!ftpClient.deleteFile(name))
                throw new ConnectionRunningException("Couldn't delete existent file: " + name);
        }

        // 2. create the empty file 
        if (!ftpClient.storeFile(name, IOUtils.toInputStream("")))
            throw new ConnectionRunningException("Couldn't create and empty file for: " + name);

        // 3. copy stream
        serverOut = new BufferedOutputStream(ftpClient.storeFileStream(name), ftpClient.getBufferSize());
        Util.copyStream(in, serverOut, ftpClient.getBufferSize(), CopyStreamEvent.UNKNOWN_STREAM_SIZE,
                new CopyStreamAdapter() {
                    @Override
                    public void bytesTransferred(long totalBytesTransferred, int bytesTransferred,
                            long streamSize) {
                        progressAddBytes(bytesTransferred);
                    }
                });
        // not documented but necessary: flush and close the server stream !!!
        serverOut.flush();
        serverOut.close();
        if (!ftpClient.completePendingCommand()) {
            connectionManager.close();
            throw new ConnectionRunningException(
                    "[FTP] While getting/copying streams: " + ftpClient.getReplyString());
        }

    } catch (Exception e) {
        logger.error("[FTP] While getting/copying streams: " + e.getMessage(), e);
        if (!(e instanceof ConnectionException)) {
            connectionManager.close();
            throw new ConnectionRunningException("[FTP] While getting/copying streams: " + e.getMessage(), e);
        }
    } finally {
        IOUtils.closeQuietly(in);
        progressSetSubTaskMessage("");
    }
}

From source file:net.skyebook.osmgenerator.DBActions.java

private void pushBulkWayMembers() {
    if (bulkInsertWayMemberBuilder == null)
        return;// www. j  a va2  s  . c om
    try {
        InputStream is = IOUtils.toInputStream(bulkInsertWayMemberBuilder.toString());
        bulkInsertWayMember.execute("SET UNIQUE_CHECKS=0; ");
        bulkInsertWayMember.setLocalInfileInputStream(is);

        bulkInsertWayMember
                .execute("LOAD DATA LOCAL INFILE 'file.txt' INTO TABLE way_members FIELDS TERMINATED BY '"
                        + BULK_DELIMITER + "' (way, node)");

        bulkInsertWayMember.execute("SET UNIQUE_CHECKS=1; ");
        bulkInsertWayMemberBuilder = null;
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:com.github.thesmartenergy.mdq.entities.Ontology.java

@Override
public String asXML() {
    Model model = ModelFactory.createDefaultModel().read(IOUtils.toInputStream(turtle), "http://ex.org/",
            "TTL");
    StringWriter sw = new StringWriter();
    model.write(sw);//from  ww w  . jav  a2s . co m
    return sw.toString();
}