Example usage for org.apache.commons.io FileUtils openInputStream

List of usage examples for org.apache.commons.io FileUtils openInputStream

Introduction

In this page you can find the example usage for org.apache.commons.io FileUtils openInputStream.

Prototype

public static FileInputStream openInputStream(File file) throws IOException 

Source Link

Document

Opens a FileInputStream for the specified file, providing better error messages than simply calling new FileInputStream(file).

Usage

From source file:org.hibernate.search.test.bridge.tika.TikaBridgeInputTypeTest.java

private Blob dataAsBlob(File file, Session session) throws IOException {
    FileInputStream in = FileUtils.openInputStream(file);
    return session.getLobHelper().createBlob(in, file.length());
}

From source file:org.jahia.modules.gateway.JSONToJCRDeserializer.java

@Handler
public void handleExchange(final Exchange exchange) {
    if (exchange != null && exchange.getIn() != null && exchange.getIn().getBody().toString().startsWith("{")) {
        try {/*from   w  w w  .  j  av a 2  s. c  o  m*/
            String body = exchange.getIn().getBody().toString();
            final JSONObject jsonObject = new JSONObject(body);

            final String nodetype = jsonObject.getString("nodetype");
            assert nodetype != null;

            // Check that nodetype exists
            final ExtendedNodeType extendedNodeType = NodeTypeRegistry.getInstance().getNodeType(nodetype);
            assert extendedNodeType != null;
            final String name = jsonObject.getString("name");
            assert name != null;

            String username = null;
            if (jsonObject.has("username")) {
                username = jsonObject.getString("username");
            }
            String locale = jsonObject.getString("locale");
            assert locale != null;
            String workspace = jsonObject.getString("workspace");
            assert workspace != null;
            final String path = jsonObject.getString("path");
            assert path != null;
            if (!extendedNodeType.isNodeType("nt:file")) {
                final JSONObject properties = jsonObject.getJSONObject("properties");
                assert properties != null;
                jcrTemplate.doExecuteWithSystemSession(username, workspace,
                        org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(locale),
                        new JCRCallback<Object>() {
                            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                                logger.debug("Getting parent node with path : " + path);
                                boolean saveFileUnderNode = false;
                                try {
                                    if (jsonObject.has("saveFileUnderNewlyCreatedNode")) {
                                        saveFileUnderNode = jsonObject
                                                .getBoolean("saveFileUnderNewlyCreatedNode");
                                    }
                                } catch (JSONException e) {
                                    logger.error(e.getMessage(), e);
                                }
                                Object header = exchange.getIn().getHeader(Constants.UPDATE_ONLY);
                                if (header == null || !(Boolean) header) {
                                    createNewNode(session, path, name, nodetype, properties, extendedNodeType,
                                            jsonObject, saveFileUnderNode);
                                } else {
                                    updateExistingNode(session, path, name, properties, extendedNodeType,
                                            jsonObject, nodetype, saveFileUnderNode);
                                }
                                session.save();
                                return null;
                            }
                        });
            } else if (jsonObject.has("files")) {
                jcrTemplate.doExecuteWithSystemSession(username, workspace,
                        org.jahia.utils.LanguageCodeConverters.languageCodeToLocale(locale),
                        new JCRCallback<Object>() {
                            public Object doInJCR(JCRSessionWrapper session) throws RepositoryException {
                                if (logger.isDebugEnabled()) {
                                    logger.debug("Getting parent node with path : " + path);
                                }
                                try {
                                    JCRNodeWrapper node = session.getNode(path);
                                    boolean doUpdate = jsonObject.has("updateifexists")
                                            && Boolean.valueOf(jsonObject.getString("updateifexists"));
                                    JSONArray files = jsonObject.getJSONArray("files");
                                    for (int i = 0; i < files.length(); i++) {
                                        File file = null;
                                        String contentType = null;
                                        String nodeName = null;

                                        Object fileItem = files.get(i);
                                        if (fileItem instanceof JSONObject) {
                                            JSONObject fileDescriptor = (JSONObject) fileItem;
                                            file = new File(fileDescriptor.getString("file"));
                                            nodeName = StringUtils.defaultIfEmpty(fileDescriptor.has("name")
                                                    ? fileDescriptor.getString("name")
                                                    : null, file.getName());
                                            contentType = fileDescriptor.has("contentType")
                                                    ? fileDescriptor.getString("contentType")
                                                    : null;
                                        } else {
                                            file = new File(files.getString(i));
                                            nodeName = file.getName();
                                        }
                                        if (contentType == null) {
                                            contentType = JCRContentUtils.getMimeType(nodeName);
                                        }

                                        if (file == null || nodeName == null || contentType == null) {
                                            continue;
                                        }

                                        InputStream is = null;
                                        try {
                                            is = FileUtils.openInputStream(file);
                                            final JCRNodeWrapper newNode = node.uploadFile(doUpdate ? nodeName
                                                    : JCRContentUtils.findAvailableNodeName(node, nodeName), is,
                                                    contentType);
                                            if (jsonObject.has("tags")) {
                                                String siteKey = newNode.getResolveSite().getSiteKey();
                                                taggingService.tag(newNode.getPath(),
                                                        jsonObject.getString("tags"), siteKey, true, session);
                                            }
                                        } catch (IOException e) {
                                            logger.error(e.getMessage(), e);
                                        } finally {
                                            IOUtils.closeQuietly(is);
                                            FileUtils.deleteQuietly(file);
                                        }
                                    }
                                    session.save();
                                } catch (JSONException e) {
                                    logger.error(e.getMessage(), e);
                                }
                                return null;
                            }
                        });
            }
        } catch (JSONException e) {
            logger.error(e.getMessage(), e);
        } catch (NoSuchNodeTypeException e) {
            logger.error(e.getMessage(), e);
        } catch (RepositoryException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.jahia.modules.gateway.JSONToJCRDeserializer.java

private void createNewNode(JCRSessionWrapper session, String path, String name, String nodetype,
        JSONObject properties, ExtendedNodeType extendedNodeType, JSONObject jsonObject,
        boolean saveFileUnderNode) throws RepositoryException {
    JCRNodeWrapper node = session.getNode(path);
    String availableNodeName = JCRContentUtils.findAvailableNodeName(node,
            JCRContentUtils.generateNodeName(name, 32));
    logger.debug("adding subnode with name : " + availableNodeName);
    JCRNodeWrapper newNode = node.addNode(availableNodeName, nodetype);
    setPropertiesOnNode(newNode, properties, extendedNodeType);
    //Manage childs
    try {/*w w w  . j a  v  a 2s.  c  o m*/
        if (jsonObject.has("childs")) {
            JSONArray childs = jsonObject.getJSONArray("childs");
            for (int i = 0; i < childs.length(); i++) {
                JSONObject childJSONObject = childs.getJSONObject(i);
                String childNodetype = childJSONObject.getString("nodetype");
                assert childNodetype != null;
                // Check that nodetype exists
                ExtendedNodeType childNodeType = NodeTypeRegistry.getInstance().getNodeType(childNodetype);
                String childName = childJSONObject.getString("name");
                assert childName != null;
                JSONObject childProperties = childJSONObject.getJSONObject("properties");
                assert childProperties != null;
                String childAvailableNodeName = JCRContentUtils.findAvailableNodeName(node,
                        JCRContentUtils.generateNodeName(childName, 32));
                logger.debug("adding subnode with name : " + availableNodeName);
                JCRNodeWrapper childNode = newNode.addNode(childAvailableNodeName, childNodetype);
                setPropertiesOnNode(childNode, childProperties, childNodeType);
            }
        }
        if (jsonObject.has("tags")) {
            String siteKey = newNode.getResolveSite().getSiteKey();
            taggingService.tag(newNode.getPath(), jsonObject.getString("tags"), siteKey, true, session);
        }
        if (saveFileUnderNode && jsonObject.has("files")) {
            JSONArray files = jsonObject.getJSONArray("files");
            for (int i = 0; i < files.length(); i++) {
                FileInputStream is = null;
                File file = null;
                try {
                    file = new File(files.getString(i));
                    is = FileUtils.openInputStream(file);
                    newNode.uploadFile(file.getName(), is, JCRContentUtils.getMimeType(file.getName()));
                } catch (IOException e) {
                    logger.error(e.getMessage(), e);
                } finally {
                    IOUtils.closeQuietly(is);
                    FileUtils.deleteQuietly(file);
                }
            }
        }
    } catch (JSONException e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:org.jahia.modules.gateway.JSONToJCRDeserializer.java

private void setPropertiesOnNode(JCRNodeWrapper newNode, JSONObject properties, ExtendedNodeType nodeType)
        throws RepositoryException {
    Iterator keys = properties.keys();
    while (keys.hasNext()) {
        String property = (String) keys.next();
        try {//from  w ww  . jav  a  2 s  . com
            String value = (String) properties.get(property);
            boolean needUpdate;
            logger.debug("added property " + property + " with value " + value);
            String name = property.replaceAll("_", ":");
            try {
                needUpdate = !(newNode.getProperty(name).getValue().getString().equals(value));
            } catch (RepositoryException e1) {
                needUpdate = true;
            }
            if (needUpdate) {
                ExtendedPropertyDefinition propertyDefinition = nodeType.getPropertyDefinition(name);
                if (propertyDefinition == null) {
                    ExtendedNodeType[] declaredSupertypes = nodeType.getDeclaredSupertypes();
                    for (ExtendedNodeType declaredSupertype : declaredSupertypes) {
                        propertyDefinition = declaredSupertype.getPropertyDefinition(name);
                        if (propertyDefinition != null) {
                            break;
                        }
                    }
                }
                int requiredType = 0;
                if (propertyDefinition != null) {
                    requiredType = propertyDefinition.getRequiredType();
                }
                switch (requiredType) {
                case ExtendedPropertyType.DATE:
                    DateTime dateTime = ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(value);
                    newNode.setProperty(name, dateTime.toCalendar(Locale.ENGLISH));
                    break;
                case ExtendedPropertyType.REFERENCE:
                case ExtendedPropertyType.WEAKREFERENCE:
                    File file = new File(value);
                    JCRNodeWrapper files = newNode.getSession()
                            .getNode(newNode.getResolveSite().getPath() + "/files");
                    FileInputStream is = null;
                    try {
                        is = FileUtils.openInputStream(file);
                        JCRNodeWrapper reference = files.uploadFile(file.getName(), is,
                                JCRContentUtils.getMimeType(file.getName()));
                        newNode.setProperty(name, reference);
                    } finally {
                        IOUtils.closeQuietly(is);
                        FileUtils.deleteQuietly(file);
                    }
                    break;
                default:
                    newNode.setProperty(name, value);
                    break;
                }
            }
        } catch (JSONException e) {
            logger.error(e.getMessage(), e);
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        }
    }
}

From source file:org.jahia.services.importexport.DocumentViewImportHandler.java

private void uploadFile(Attributes atts, String decodedQName, String path, JCRNodeWrapper child)
        throws IOException, RepositoryException {
    if (!expandImportedFilesOnDisk) {
        boolean contentFound = findContent();
        if (contentFound) {
            uploadFile(atts, decodedQName, path, child, zis);
            zis.close();// www  .j a v a 2 s  .  c  om
        }
    } else {
        String contentInExpandedPath = findContentInExpandedPath();
        if (contentInExpandedPath != null) {
            final InputStream is = FileUtils
                    .openInputStream(new File(expandImportedFilesOnDiskPath + contentInExpandedPath));
            uploadFile(atts, decodedQName, path, child, is);
            is.close();
        }
    }
}

From source file:org.jahia.services.scheduler.JSR223ScriptJob.java

@Override
public void executeJahiaJob(JobExecutionContext jobExecutionContext) throws Exception {
    final JobDataMap map = jobExecutionContext.getJobDetail().getJobDataMap();
    String jobScriptPath;/*ww w .jav a  2  s.  c om*/
    boolean isAbsolutePath = false;
    if (map.containsKey(JOB_SCRIPT_ABSOLUTE_PATH)) {
        isAbsolutePath = true;
        jobScriptPath = map.getString(JOB_SCRIPT_ABSOLUTE_PATH);
    } else {
        jobScriptPath = map.getString(JOB_SCRIPT_PATH);
    }
    logger.info("Start executing JSR223 script job {}", jobScriptPath);

    ScriptEngine scriptEngine = ScriptEngineUtils.getInstance()
            .scriptEngine(FilenameUtils.getExtension(jobScriptPath));
    if (scriptEngine != null) {
        ScriptContext scriptContext = new SimpleScriptContext();
        final Bindings bindings = new SimpleBindings();
        bindings.put("jobDataMap", map);

        InputStream scriptInputStream;
        if (!isAbsolutePath) {
            scriptInputStream = JahiaContextLoaderListener.getServletContext()
                    .getResourceAsStream(jobScriptPath);
        } else {
            scriptInputStream = FileUtils.openInputStream(new File(jobScriptPath));
        }
        if (scriptInputStream != null) {
            Reader scriptContent = null;
            try {
                scriptContent = new InputStreamReader(scriptInputStream);
                StringWriter out = new StringWriter();
                scriptContext.setWriter(out);
                // The following binding is necessary for Javascript, which doesn't offer a console by default.
                bindings.put("out", new PrintWriter(scriptContext.getWriter()));
                scriptContext.setBindings(bindings, ScriptContext.ENGINE_SCOPE);
                scriptContext.setBindings(scriptEngine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE),
                        ScriptContext.GLOBAL_SCOPE);
                scriptEngine.eval(scriptContent, scriptContext);
                map.put(JOB_SCRIPT_OUTPUT, out.toString());
                logger.info("...JSR-223 script job {} execution finished", jobScriptPath);
            } catch (ScriptException e) {
                logger.error("Error during execution of the JSR-223 script job " + jobScriptPath
                        + " execution failed with error " + e.getMessage(), e);
                throw new Exception("Error during execution of script " + jobScriptPath, e);
            } finally {
                if (scriptContent != null) {
                    IOUtils.closeQuietly(scriptContent);
                }
            }
        }
    }
}

From source file:org.jahia.utils.maven.plugin.resources.JavaScriptDictionaryMojo.java

protected static ResourceBundle lookupBundle(File src, String resourceBundle, String... locales)
        throws IOException {
    ResourceBundle rb = null;//from w w  w.  j  a  va  2 s  .  co  m
    for (String locale : locales) {
        File f = new File(src, resourceBundle + "_" + locale + ".properties");
        if (f.exists()) {
            InputStream is = null;
            try {
                is = FileUtils.openInputStream(f);
                rb = new PropertyResourceBundle(is);
                break;
            } finally {
                IOUtils.closeQuietly(is);
            }
        }
    }
    return rb;
}

From source file:org.jamwiki.utils.ResourceUtil.java

/**
 * Utility method for reading a file from a classpath directory and returning
 * its contents as a String./*from  w  ww. j  a  v a2 s.  com*/
 *
 * @param filename The name of the file to be read, either as an absolute file
 *  path or relative to the classpath.
 * @return A string representation of the file contents.
 * @throws IOException Thrown if the file cannot be found or if an I/O exception
 *  occurs.
 */
public static String readFile(String filename) throws IOException {
    File file = new File(filename);
    if (!file.exists()) {
        // look for file in resource directories
        file = getClassLoaderFile(filename);
    }
    InputStream is = null;
    try {
        is = new BOMInputStream(FileUtils.openInputStream(file));
        return IOUtils.toString(is, "UTF-8");
    } finally {
        if (null != is) {
            IOUtils.closeQuietly(is);
            is = null;
        }
    }
}

From source file:org.jboss.windup.metadata.type.XmlMetadata.java

protected Document hydrateDocument() {
    if (parsedDocumentRef == null) {
        FileInputStream fis = null;
        try {//from  www. j a  v  a2 s  .co m
            fis = FileUtils.openInputStream(filePointer);
            Document parsedDocument = LocationAwareXmlReader.readXML(fis);

            LOG.debug("Hydrating XML Document: " + filePointer.getAbsolutePath());
            parsedDocumentRef = new SoftReference<Document>(parsedDocument);
        } catch (Exception e) {
            LOG.error("Bad XML? " + filePointer.getAbsolutePath());
            LOG.info("Skipping file. Continuing Windup Processing...");

            Summary sr = new Summary();
            sr.setDescription("Bad XML? Unable to parse.");
            sr.setLevel(NotificationLevel.CRITICAL);
            sr.setEffort(new UnknownEffort());
            this.getDecorations().add(sr);
            this.parsedDocumentRef = null;

            return null;
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
    return parsedDocumentRef.get();
}

From source file:org.jboss.windup.resource.type.XmlMeta.java

protected Document hydrateDocument() {
    if (parsedDocumentRef == null) {
        FileInputStream fis = null;
        try {// w w  w  .  jav a 2s  . c o  m
            fis = FileUtils.openInputStream(filePointer);
            Document parsedDocument = PositionalXmlReader.readXML(fis);

            LOG.debug("Hydrating XML Document: " + filePointer.getAbsolutePath());
            parsedDocumentRef = new SoftReference<Document>(parsedDocument);
        } catch (Exception e) {
            LOG.error("Bad XML? " + filePointer.getAbsolutePath());
            LOG.info("Skipping file. Continuing Windup Processing...");

            Summary sr = new Summary();
            sr.setDescription("Bad XML? Unable to parse.");
            sr.setLevel(NotificationLevel.CRITICAL);
            sr.setEffort(new UnknownEffort());
            this.getDecorations().add(sr);
            this.parsedDocumentRef = null;

            return null;
        } finally {
            IOUtils.closeQuietly(fis);
        }
    }
    return parsedDocumentRef.get();
}