Example usage for org.springframework.core.io Resource exists

List of usage examples for org.springframework.core.io Resource exists

Introduction

In this page you can find the example usage for org.springframework.core.io Resource exists.

Prototype

boolean exists();

Source Link

Document

Determine whether this resource actually exists in physical form.

Usage

From source file:org.impalaframework.module.source.BaseInternalModuleDefinitionSource.java

URL getResourceForModule(String moduleName, String resourceName) {
    URL resource = ModuleResourceUtils.loadModuleResource(moduleLocationResolver, moduleName, resourceName);

    if (resource == null) {
        final List<Resource> classLocations = moduleLocationResolver
                .getApplicationModuleClassLocations(moduleName);

        logger.error("Problem locating resources for module: " + moduleName + ". Locations being searched are "
                + (classLocations.isEmpty() ? "empty" : "listed next:"));
        for (Resource classLocation : classLocations) {
            logger.error(classLocation.getDescription()
                    + (classLocation.exists() ? ": is present on file system" : " cannot be found"));
        }/*  ww  w . j  a v a2s . c  o m*/

        throw new ConfigurationException("Application is using internally defined module structure, but no "
                + MODULE_PROPERTIES + " file is present on the classpath for module '" + moduleName
                + "'. It must exist in one of the following locations: " + classLocations);
    }
    return resource;
}

From source file:org.impalaframework.spring.bean.OptionalPropertiesFactoryBean.java

@Override
public void setLocation(Resource location) {
    if (location.exists())
        super.setLocations(new Resource[] { location });
    else {//from www. j a  v a  2s  .c o  m
        logger.info("Unable to locate resource location with location " + location);
    }
}

From source file:org.impalaframework.spring.bean.OptionalPropertiesFactoryBean.java

@Override
public void setLocations(Resource[] locations) {
    List<Resource> resources = new ArrayList<Resource>();
    for (int i = 0; i < locations.length; i++) {
        final Resource resource = locations[i];
        if (resource.exists()) {
            resources.add(resource);//from ww  w.  j a v a 2s .  c  o  m
            if (logger.isDebugEnabled())
                logger.debug("Extracting properties from resource " + resource.getDescription());
        } else {
            logger.info("Not extracting properties from resource " + resource.getDescription()
                    + " as this resource does not exist");
        }
    }
    Resource[] existingArray = new Resource[resources.size()];
    resources.toArray(existingArray);
    super.setLocations(existingArray);
}

From source file:org.impalaframework.spring.ExtendedPropertyPlaceholderConfigurer.java

protected List<Resource> getLocations(String folderLocation, String suppliedFileLocation) {
    List<Resource> resources = new ArrayList<Resource>();
    String fileLocation = suppliedFileLocation;

    boolean classPathLocation = false;

    // strip off classpath
    if (fileLocation.startsWith(CLASSPATH_PREFIX)) {
        classPathLocation = true;//from www . j  av a  2 s. co  m
        fileLocation = fileLocation.substring(CLASSPATH_PREFIX.length());
    }

    Resource classPathResource = getClassPathResource(suppliedFileLocation, fileLocation);

    if (classPathResource.exists()) {
        // find the classpath resource
        resources.add(classPathResource);
    }

    if (classPathLocation)
        return resources;

    if (null != folderLocation) {
        addFileResources(folderLocation, resources, fileLocation);
    }
    return resources;
}

From source file:org.impalaframework.util.XMLDomUtils.java

/**
 * Validates document of given description using w3c.org schema validation
 * @param document the DOM document instance
 * @param description a description of the document, typically name or path
 * @param xsdResource the schema resource used for validation
 *//* ww  w .  j a  v  a 2s  .  c o m*/
public static void validateDocument(Document document, String description, Resource xsdResource) {

    Assert.notNull(xsdResource, "xsdResource cannot be null");

    if (!xsdResource.exists()) {
        throw new ExecutionException(
                "Cannot validate document as xsdResource '" + xsdResource + "' does not exist");
    } else {
        if (logger.isDebugEnabled()) {
            logger.debug("Validating using schema resource " + xsdResource.getDescription());
        }
    }

    SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);

    try {
        InputStream inputStream = xsdResource.getInputStream();
        Source source = new StreamSource(inputStream);

        Schema schema = factory.newSchema(source);
        Validator validator = schema.newValidator();
        validator.validate(new DOMSource(document));
    } catch (SAXParseException e) {
        throw new ExecutionException("Error on " + e.getLineNumber() + ", column " + e.getColumnNumber()
                + " in " + description + ": " + e.getMessage(), e);
    } catch (SAXException e) {
        throw new ExecutionException("Error parsing " + description + ": " + e.getMessage(), e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.impalaframework.web.module.monitor.BaseStagingFileModuleRuntimeMonitor.java

int maybeCopyToResource(Resource resource, File file) {

    int result = 0;
    final Resource tempFileResource = getTempFileResource(resource);
    if (tempFileResource.exists()) {
        final File tempFile = getFileFromResource(tempFileResource);

        File backup = new File(file.getParentFile(), file.getName() + ".backup");
        boolean renamed = file.renameTo(backup);

        try {/*from  w  w  w  .ja v a 2s  .co  m*/
            FileCopyUtils.copy(tempFile, file);
            result++;

            if (renamed) {
                backup.delete();
                tempFile.delete();
                result++;
            }

        } catch (IOException e) {
            logger.error("Unable to copy '" + tempFile + "' to '" + file + "'", e);

            result--;

            //set backup back to renamed file
            if (renamed) {
                result--;
                final boolean renamedBack = backup.renameTo(file);
                if (renamedBack) {
                    result--;
                }
            }
        }
    }

    //0 no tempfile present
    //1 means file was copied but no backup could be taken
    //2 means file was copied and backup was taken
    //-1 means that copy failed and no backup was taken
    //-2 means copy failed, backup taken but could not be renamed back
    //-3 means copy failed, backup taken and renamed back

    return result;
}

From source file:org.jahia.services.content.nodetypes.initializers.ScriptChoiceListInitializerImpl.java

public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition epd, String param,
        List<ChoiceListValue> values, Locale locale, Map<String, Object> context) {
    if (param != null) {
        final String extension = Patterns.DOT.split(param)[1];
        ScriptEngine byName;// w w  w.  jav a 2 s  .co  m
        try {
            byName = scriptEngineUtils.scriptEngine(extension);
        } catch (ScriptException e) {
            logger.error(e.getMessage(), e);
            byName = null;
        }
        if (byName != null) {
            final Set<JahiaTemplatesPackage> forModule = ServicesRegistry.getInstance()
                    .getJahiaTemplateManagerService().getModulesWithViewsForComponent(
                            JCRContentUtils.replaceColon(epd.getDeclaringNodeType().getName()));
            final Bindings bindings = byName.getBindings(ScriptContext.ENGINE_SCOPE);
            bindings.put("values", values);
            for (JahiaTemplatesPackage template : forModule) {
                final Resource scriptPath = template
                        .getResource(File.separator + "scripts" + File.separator + param);
                if (scriptPath != null && scriptPath.exists()) {
                    Reader scriptContent = null;
                    try {
                        scriptContent = new InputStreamReader(scriptPath.getInputStream());
                        return (List<ChoiceListValue>) byName.eval(scriptContent, bindings);
                    } catch (ScriptException e) {
                        logger.error("Error while executing script " + scriptPath, e);
                    } catch (IOException e) {
                        logger.error(e.getMessage(), e);
                    } finally {
                        if (scriptContent != null) {
                            IOUtils.closeQuietly(scriptContent);
                        }
                    }
                }
            }
        }
    }
    return Collections.emptyList();
}

From source file:org.jahia.services.content.nodetypes.initializers.TemplatesChoiceListInitializerImpl.java

public List<ChoiceListValue> getChoiceListValues(ExtendedPropertyDefinition declaringPropertyDefinition,
        String param, List<ChoiceListValue> values, Locale locale, Map<String, Object> context) {
    if (context == null) {
        return new ArrayList<ChoiceListValue>();
    }/* ww w .  j av  a  2  s .  c  o  m*/
    JCRNodeWrapper node = (JCRNodeWrapper) context.get("contextNode");
    JCRNodeWrapper parentNode = (JCRNodeWrapper) context.get("contextParent");
    ExtendedNodeType realNodeType = (ExtendedNodeType) context.get("contextType");
    String propertyName = context.containsKey("dependentProperties")
            ? ((List<String>) context.get("dependentProperties")).get(0)
            : null;

    JCRSiteNode site = null;

    SortedSet<View> views = new TreeSet<View>();

    boolean subViews = false;

    try {
        if (node != null) {
            site = node.getResolveSite();
        }
        if (site == null && parentNode != null) {
            site = parentNode.getResolveSite();
        }

        final List<String> nodeTypeList = new ArrayList<String>();
        String nextParam = "";
        if (param.contains(",")) {
            nextParam = StringUtils.substringAfter(param, ",");
            param = StringUtils.substringBefore(param, ",");
        }
        if ("subnodes".equals(param)) {
            subViews = true;
            if (propertyName == null) {
                propertyName = "j:allowedTypes";
            }
            if (context.containsKey(propertyName)) {
                List<String> types = (List<String>) context.get(propertyName);
                for (String type : types) {
                    nodeTypeList.add(type);
                }
            } else if (node != null && node.hasProperty(propertyName)) {
                JCRPropertyWrapper property = node.getProperty(propertyName);
                if (property.isMultiple()) {
                    Value[] types = property.getValues();
                    for (Value type : types) {
                        nodeTypeList.add(type.getString());
                    }
                } else {
                    nodeTypeList.add(property.getValue().getString());
                }
            } else if (node != null && !"j:allowedTypes".equals(propertyName)
                    && node.hasProperty("j:allowedTypes")) {
                Value[] types = node.getProperty("j:allowedTypes").getValues();
                for (Value type : types) {
                    nodeTypeList.add(type.getString());
                }
            } else if (node != null) {
                // No restrictions get node type list from already existing nodes
                NodeIterator nodeIterator = node.getNodes();
                while (nodeIterator.hasNext()) {
                    Node next = (Node) nodeIterator.next();
                    String name = next.getPrimaryNodeType().getName();
                    if (!nodeTypeList.contains(name) && next.isNodeType("jnt:content")) {
                        nodeTypeList.add(name);
                    }
                }
            }
            param = nextParam;
        } else if ("reference".equals(param)) {
            if (propertyName == null) {
                propertyName = Constants.NODE;
            }
            if (context.containsKey(propertyName)) {
                JCRSessionWrapper session = JCRSessionFactory.getInstance().getCurrentUserSession();
                List<String> refNodeUuids = (List<String>) context.get(propertyName);
                for (String refNodeUuid : refNodeUuids) {
                    try {
                        JCRNodeWrapper refNode = session.getNodeByUUID(refNodeUuid);
                        nodeTypeList.addAll(refNode.getNodeTypes());
                    } catch (Exception e) {
                        logger.warn("Referenced node not found to retrieve its nodetype for initializer", e);
                    }
                }
            } else if (node != null && node.hasProperty(propertyName)) {
                try {
                    JCRNodeWrapper refNode = (JCRNodeWrapper) node.getProperty(propertyName).getNode();
                    nodeTypeList.addAll(refNode.getNodeTypes());
                } catch (ItemNotFoundException e) {
                }
            } else if (node != null && !Constants.NODE.equals(propertyName)
                    && node.hasProperty(Constants.NODE)) {
                try {
                    JCRNodeWrapper refNode = (JCRNodeWrapper) node.getProperty(Constants.NODE).getNode();
                    nodeTypeList.addAll(refNode.getNodeTypes());
                } catch (ItemNotFoundException e) {
                }
            }
            param = nextParam;
        } else if ("mainresource".equals(param)) {
            JCRNodeWrapper matchingParent;
            JCRNodeWrapper parent;
            if (node == null) {
                parent = (JCRNodeWrapper) context.get("contextParent");
                site = parent.getResolveSite();
            } else {
                parent = node.getParent();
            }
            try {
                while (true) {
                    if (parent.isNodeType("jnt:template")) {
                        matchingParent = parent;
                        break;
                    }
                    parent = parent.getParent();
                }
                if (matchingParent.hasProperty("j:applyOn")) {
                    Value[] vs = matchingParent.getProperty("j:applyOn").getValues();
                    for (Value v : vs) {
                        nodeTypeList.add(v.getString());
                    }
                }
            } catch (ItemNotFoundException e) {
            }
            if (nodeTypeList.isEmpty()) {
                nodeTypeList.add("jnt:page");
            }
            param = nextParam;
        } else if (param != null && param.indexOf(":") > 0) {
            nodeTypeList.add(param);
            param = nextParam;
        } else {
            if (node != null) {
                nodeTypeList.addAll(node.getNodeTypes());
            } else if (realNodeType != null) {
                nodeTypeList.add(realNodeType.getName());
            }
        }

        if (nodeTypeList.isEmpty()) {
            nodeTypeList.add("nt:base");
        }

        SortedSet<ViewWrapper> wrappedViews = new TreeSet<ViewWrapper>();
        Set<ViewWrapper> wrappedViewsSet = new HashSet<ViewWrapper>();
        for (String s : nodeTypeList) {
            SortedSet<View> viewsSet = RenderService.getInstance()
                    .getViewsSet(NodeTypeRegistry.getInstance().getNodeType(s), site, "html");

            if (!viewsSet.isEmpty()) {
                // use of wrapper class to get a simpler equals method, based on the key
                // to keep only views in common between sub nodes
                for (Iterator<View> iterator = viewsSet.iterator(); iterator.hasNext();) {
                    wrappedViewsSet.add(new ViewWrapper(iterator.next()));
                }

                if (subViews && !wrappedViews.isEmpty()) {
                    wrappedViews.retainAll(wrappedViewsSet);
                } else {
                    wrappedViews.addAll(wrappedViewsSet);
                }
            }
            wrappedViewsSet.clear();
        }

        for (Iterator<ViewWrapper> iterator = wrappedViews.iterator(); iterator.hasNext();) {
            views.add(iterator.next().getView());
        }

    } catch (RepositoryException e) {
        logger.error(e.getMessage(), e);
    }

    List<ChoiceListValue> vs = new ArrayList<ChoiceListValue>();
    for (View view : views) {
        HashMap<String, Object> map = new HashMap<String, Object>();
        fillProperties(map, view.getDefaultProperties());
        fillProperties(map, view.getProperties());
        boolean isStudio = site != null && site.getPath().startsWith("/modules");
        if (isViewVisible(view.getKey(), param, map, isStudio)) {
            JahiaTemplatesPackage pkg = view.getModule() != null ? view.getModule()
                    : ServicesRegistry.getInstance().getJahiaTemplateManagerService()
                            .getTemplatePackageById(JahiaTemplatesPackage.ID_DEFAULT);
            String displayName = Messages.get(pkg, declaringPropertyDefinition.getResourceBundleKey() + "."
                    + JCRContentUtils.replaceColon(view.getKey()), locale, view.getKey());
            ChoiceListValue c = new ChoiceListValue(displayName, map,
                    new ValueImpl(view.getKey(), PropertyType.STRING, false));
            try {
                final Resource imagePath = pkg.getResource(
                        File.separator + "img" + File.separator + c.getValue().getString() + ".png");

                if (imagePath != null && imagePath.exists()) {
                    String s = Jahia.getContextPath();
                    if (s.equals("/")) {
                        s = "";
                    }
                    c.addProperty("image", s + (pkg.getRootFolderPath().startsWith("/") ? "" : "/")
                            + pkg.getRootFolderPath() + "/img/" + c.getValue().getString() + ".png");
                }
            } catch (RepositoryException e) {
                logger.error(e.getMessage(), e);
            }

            vs.add(c);
        }
    }
    Collections.sort(vs);
    return vs;
}

From source file:org.jahia.services.sites.JahiaSitesService.java

public JahiaSite addSite(JahiaUser currentUser, String title, String serverName, String siteKey, String descr,
        Locale selectedLocale, String selectTmplSet, final String[] modulesToDeploy, String firstImport,
        Resource fileImport, String fileImportName, Boolean asAJob, Boolean doImportServerPermissions,
        String originatingJahiaRelease, Resource legacyMappingFilePath, Resource legacyDefinitionsFilePath,
        JCRSessionWrapper session) throws JahiaException, IOException {

    // check there is no site with same server name before adding
    boolean importingSystemSite = false;
    final JahiaTemplateManagerService templateService = ServicesRegistry.getInstance()
            .getJahiaTemplateManagerService();
    JCRSiteNode site = null;//  w  ww .j  a  v a 2 s .c o m

    try {

        if (!siteExists(siteKey, session)) {

            final JahiaTemplatesPackage templateSet = templateService
                    .getAnyDeployedTemplatePackage(selectTmplSet);
            final String templatePackage = templateSet.getId();

            JCRNodeWrapper sitesFolder = session.getNode("/sites");

            try {
                sitesFolder.getNode(siteKey);
                throw new IOException("site already exists");
            } catch (PathNotFoundException e) {

                JCRNodeWrapper siteNode = sitesFolder.addNode(siteKey, "jnt:virtualsite");

                if (sitesFolder.hasProperty("j:virtualsitesFolderSkeleton")) {
                    String skeletons = sitesFolder.getProperty("j:virtualsitesFolderSkeleton").getString();
                    try {
                        JCRContentUtils.importSkeletons(skeletons, sitesFolder.getPath() + "/" + siteKey,
                                session);
                    } catch (Exception importEx) {
                        logger.error("Unable to import data using site skeleton " + skeletons, importEx);
                    }
                }

                siteNode.setProperty("j:title", title);
                siteNode.setProperty("j:description", descr);
                siteNode.setProperty("j:serverName", serverName);
                siteNode.setProperty(SitesSettings.DEFAULT_LANGUAGE, selectedLocale.toString());
                siteNode.setProperty(SitesSettings.MIX_LANGUAGES_ACTIVE, false);
                siteNode.setProperty(SitesSettings.LANGUAGES, new String[] { selectedLocale.toString() });
                siteNode.setProperty(SitesSettings.INACTIVE_LIVE_LANGUAGES, new String[] {});
                siteNode.setProperty(SitesSettings.INACTIVE_LANGUAGES, new String[] {});
                siteNode.setProperty(SitesSettings.MANDATORY_LANGUAGES, new String[] {});
                siteNode.setProperty("j:templatesSet", templatePackage);

                siteNode.setProperty("j:installedModules", new Value[] { session.getValueFactory()
                        .createValue(templatePackage /*+ ":" + aPackage.getLastVersion()*/) });

                String target = getTargetString(siteKey);

                deployModules(target, modulesToDeploy, templateSet, session, templateService);

                //Auto deploy all modules that define this behavior on site creation
                final List<JahiaTemplatesPackage> availableTemplatePackages = templateService
                        .getAvailableTemplatePackages();
                for (JahiaTemplatesPackage availableTemplatePackage : availableTemplatePackages) {
                    String autoDeployOnSite = availableTemplatePackage.getAutoDeployOnSite();
                    if (autoDeployOnSite != null
                            && ("all".equals(autoDeployOnSite) || siteKey.equals(autoDeployOnSite)
                                    || (siteKey.equals("systemsite") && autoDeployOnSite.equals("system")))) {
                        String source = "/modules/" + availableTemplatePackage.getId();
                        try {
                            logger.info("Deploying module {} to {}", source, target);
                            templateService.installModule(availableTemplatePackage, target, session);
                        } catch (RepositoryException re) {
                            logger.error("Unable to deploy module " + source + " to " + target + ". Cause: "
                                    + re.getMessage(), re);
                        }
                    }
                }
                site = (JCRSiteNode) siteNode;
            }

            session.save();
        } else if (siteKey.equals(SYSTEM_SITE_KEY)) {
            site = (JCRSiteNode) getSiteByKey(SYSTEM_SITE_KEY);
            importingSystemSite = true;
        } else {
            throw new IOException("site already exists");
        }

        JCRSiteNode siteNode = (JCRSiteNode) session.getNode(site.getPath());

        // continue if the site is added correctly...
        if (!site.isDefault() && !site.getSiteKey().equals(SYSTEM_SITE_KEY) && getNbSites() == 2) {
            setDefaultSite(site, session);
        }

        if (!importingSystemSite) {

            JahiaGroupManagerService jgms = ServicesRegistry.getInstance().getJahiaGroupManagerService();

            siteNode.setMixLanguagesActive(false);
            session.save();

            JCRGroupNode privGroup = jgms.lookupGroup(null, JahiaGroupManagerService.PRIVILEGED_GROUPNAME,
                    session);
            if (privGroup == null) {
                privGroup = jgms.createGroup(null, JahiaGroupManagerService.PRIVILEGED_GROUPNAME, null, true,
                        session);
            }

            JCRGroupNode adminGroup = jgms.lookupGroup(site.getSiteKey(),
                    JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME, session);
            if (adminGroup == null) {
                adminGroup = jgms.createGroup(site.getSiteKey(),
                        JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME, null, false, session);
            }

            // attach superadmin user (current) to administrators group...
            if (currentUser != null) {
                adminGroup.addMember(session.getNode(currentUser.getLocalPath()));
            }

            JCRGroupNode sitePrivGroup = jgms.lookupGroup(site.getSiteKey(),
                    JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, session);
            if (sitePrivGroup == null) {
                sitePrivGroup = jgms.createGroup(site.getSiteKey(),
                        JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME, null, false, session);
            }
            // atach site privileged group to server privileged
            privGroup.addMember(sitePrivGroup);

            if (!siteKey.equals(SYSTEM_SITE_KEY)) {
                siteNode.grantRoles("g:" + JahiaGroupManagerService.SITE_PRIVILEGED_GROUPNAME,
                        Collections.singleton("privileged"));
                siteNode.denyRoles("g:" + JahiaGroupManagerService.PRIVILEGED_GROUPNAME,
                        Collections.singleton("privileged"));
            }
            siteNode.grantRoles("g:" + JahiaGroupManagerService.SITE_ADMINISTRATORS_GROUPNAME,
                    Collections.singleton("site-administrator"));
            session.save();
        }

        Resource initialZip = null;
        if ("fileImport".equals(firstImport)) {
            initialZip = fileImport;
        }

        if ("importRepositoryFile".equals(firstImport)
                || (initialZip != null && initialZip.exists() && !"noImport".equals(firstImport))) {
            try {
                Map<Object, Object> importInfos = new HashMap<Object, Object>();
                importInfos.put("originatingJahiaRelease", originatingJahiaRelease);
                ServicesRegistry.getInstance().getImportExportService().importSiteZip(initialZip, site,
                        importInfos, legacyMappingFilePath, legacyDefinitionsFilePath, session);
            } catch (RepositoryException e) {
                logger.warn("Error importing site ZIP", e);
            }
        }

        logger.debug("Site updated with Home Page");
    } catch (RepositoryException e) {
        logger.warn("Error adding home node", e);
    }

    return site;
}

From source file:org.jahia.settings.SettingsBean.java

public File getRepositoryHome() throws IOException {
    String path = getString("jahia.jackrabbit.home", null);
    if (path == null) {
        path = interpolate("${jahia.data.dir}/repository");
    }/* www.  j  av  a2 s  .c  om*/
    File repoHome = new File(path);
    if (!repoHome.isAbsolute()) {
        Resource r = applicationContext.getResource(path);
        if (r != null && r.exists()) {
            repoHome = r.getFile();
        }
    }
    return repoHome.exists() ? repoHome.getAbsoluteFile() : null;
}