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.atricore.idbus.kernel.planning.jbpm.OsgiProcessFragmentRegistryApplicationContext.java

protected Resource[] getConfigResources() {

    List<Resource> resources = new ArrayList<Resource>();

    try {/*from   ww  w .j  av a2s.com*/
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                Thread.currentThread().getContextClassLoader());

        Collections.addAll(resources, resolver.getResources(DEFAULT_JBPM_FRAGMENT_CFG_FILE));

        Resource[] exts = resolver.getResources(DEFAULT_JBPM_EXT_FRAGMENT_CFG_FILE);
        for (Resource r : exts) {
            InputStream is = r.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = rd.readLine();
            while (line != null) {
                if (!"".equals(line)) {
                    resources.add(resolver.getResource(line));
                }
                line = rd.readLine();
            }
            is.close();
        }

    } catch (IOException ex) {
        // ignore
    }

    if (null == cfgFiles) {
        cfgFiles = new String[] { DEFAULT_PROCESS_DESCRIPTOR_FILE };
    }

    for (String cfgFile : cfgFiles) {
        boolean found = false;
        Resource cpr = new ClassPathResource(cfgFile);
        if (!cpr.exists()) {
            try {
                //see if it's a URL
                URL url = new URL(cfgFile);
                cpr = new UrlResource(url);
                if (cpr.exists()) {
                    resources.add(cpr);
                    found = true;
                }
            } catch (MalformedURLException e) {
                //ignore
            }
            if (!found) {
                //try loading it our way
                URL url = getResource(cfgFile, this.getClass());
                if (url != null) {
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        resources.add(cpr);
                        found = true;
                    }
                }
            }
        } else {
            resources.add(cpr);
            found = true;
        }
        if (!found) {
            logger.warn("No Process Descriptor found: " + cfgFile);
        }
    }

    if (null != cfgFileURLs) {
        for (URL cfgFileURL : cfgFileURLs) {
            UrlResource ur = new UrlResource(cfgFileURL);
            if (ur.exists()) {
                resources.add(ur);
            } else {
                logger.warn("No Process Descriptor found: " + cfgFileURL);
            }
        }
    }

    logger.info("Creating application context with resources: " + resources);

    if (0 == resources.size()) {
        return null;
    }

    Resource[] res = new Resource[resources.size()];
    res = resources.toArray(res);
    return res;
}

From source file:org.atricore.idbus.kernel.planning.jbpm.ProcessFragmentRegistryApplicationContext.java

@Override
protected Resource[] getConfigResources() {

    List<Resource> resources = new ArrayList<Resource>();

    try {//from  w ww .j ava2s  .c o  m
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                Thread.currentThread().getContextClassLoader());

        Collections.addAll(resources, resolver.getResources(DEFAULT_JBPM_FRAGMENT_CFG_FILE));

        Resource[] exts = resolver.getResources(DEFAULT_JBPM_EXT_FRAGMENT_CFG_FILE);
        for (Resource r : exts) {
            InputStream is = r.getInputStream();
            BufferedReader rd = new BufferedReader(new InputStreamReader(is, "UTF-8"));
            String line = rd.readLine();
            while (line != null) {
                if (!"".equals(line)) {
                    resources.add(resolver.getResource(line));
                }
                line = rd.readLine();
            }
            is.close();
        }

    } catch (IOException ex) {
        // ignore
    }

    if (null == cfgFiles) {
        cfgFiles = new String[] { DEFAULT_PROCESS_DESCRIPTOR_FILE };
    }

    for (String cfgFile : cfgFiles) {
        boolean found = false;
        Resource cpr = new ClassPathResource(cfgFile);
        if (!cpr.exists()) {
            try {
                //see if it's a URL
                URL url = new URL(cfgFile);
                cpr = new UrlResource(url);
                if (cpr.exists()) {
                    resources.add(cpr);
                    found = true;
                }
            } catch (MalformedURLException e) {
                //ignore
            }
            if (!found) {
                //try loading it our way
                URL url = getResource(cfgFile, this.getClass());
                if (url != null) {
                    cpr = new UrlResource(url);
                    if (cpr.exists()) {
                        resources.add(cpr);
                        found = true;
                    }
                }
            }
        } else {
            resources.add(cpr);
            found = true;
        }
        if (!found) {
            logger.warn("No Process Descriptor found: " + cfgFile);
        }
    }

    if (null != cfgFileURLs) {
        for (URL cfgFileURL : cfgFileURLs) {
            UrlResource ur = new UrlResource(cfgFileURL);
            if (ur.exists()) {
                resources.add(ur);
            } else {
                logger.warn("No Process Descriptor found: " + cfgFileURL);
            }
        }
    }

    logger.info("Creating application context with resources: " + resources);

    if (0 == resources.size()) {
        return null;
    }

    Resource[] res = new Resource[resources.size()];
    res = resources.toArray(res);
    return res;
}

From source file:org.betaconceptframework.astroboa.engine.jcr.identitystore.jackrabbit.JackrabbitIdentityStoreDao.java

private ContentObject importRole(Resource roleXmlResource, String systemUserId, String cmsRepositoryId,
        String idOfTheRepositoryWhichRepresentsTheIdentityStore) throws Exception {

    if (roleXmlResource == null || !roleXmlResource.exists()) {
        throw new CmsException("No roles xml file found");
    } else {/*from   ww  w  .j  a  va2 s. co  m*/

        String roleName = StringUtils.substringBeforeLast(roleXmlResource.getFilename(),
                CmsConstants.PERIOD_DELIM);

        String roleAffilitation = CmsRoleAffiliationFactory.INSTANCE
                .getCmsRoleAffiliationForRepository(CmsRole.valueOf(roleName), cmsRepositoryId);

        CmsOutcome<ContentObject> outcome = findRole(roleAffilitation);

        if (outcome != null && outcome.getCount() > 0) {

            if (outcome.getCount() > 1) {
                logger.warn("Found more than one roles with system name " + roleAffilitation
                        + " Will use first role available");
            }

            return outcome.getResults().get(0);
        }

        logger.info("Role {} for identity store not found. Creating one", roleAffilitation);

        InputStream inputStream = null;

        try {
            inputStream = roleXmlResource.getInputStream();

            String roleXml = IOUtils.toString(inputStream, "UTF-8");

            //Replace ids
            roleXml = StringUtils.replace(roleXml, SYSTEM_USER_ID, systemUserId);
            roleXml = StringUtils.replace(roleXml, roleName, roleAffilitation);
            roleXml = StringUtils.replace(roleXml, IDENTITY_STORE_REPOSITORY_ID,
                    idOfTheRepositoryWhichRepresentsTheIdentityStore);

            /*
             * Currently, the identifier of the repository which represents the identity store
             * is used in accessibility.canBeUpdated / accessibility.canBeDeleted properties
             * whose value follows the pattern ROLE_CMS_IDENTITY_STORE_EDITOR@IDENTITY_STORE_REPOSITORY_ID. 
             * In the case of the ROLE_CMS_IDENTITY_STORE_EDITOR.xml template, 
             * the replacements above will generate the outcome 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@<idOfTheRepositoryWhichRepresentsTheIdentityStore>
             * 
             * That is happening because the role name ROLE_CMS_IDENTITY_STORE_EDITOR is replaced once
             * by the roleAffiliation (roleName + repositoryId)   
             * 
             *    roleXml = StringUtils.replace(roleXml, roleName, roleAffilitation);
             * 
             *     ROLE_CMS_IDENTITY_STORE_EDITOR@IDENTITY_STORE_REPOSITORY_ID becomes
             * 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@IDENTITY_STORE_REPOSITORY_ID
             * 
             * and then the following replacement is executed
             * 
             * roleXml = StringUtils.replace(roleXml, IDENTITY_STORE_REPOSITORY_ID, idOfTheRepositoryWhichRepresentsTheIdentityStore);
             * 
             * to produce the following result 
             * 
             * ROLE_CMS_IDENTITY_STORE_EDITOR@<cmsRepositoryId>@<idOfTheRepositoryWhichRepresentsTheIdentityStore>
             */

            if (StringUtils.contains(roleXml,
                    "@" + cmsRepositoryId + "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore)) {
                roleXml = StringUtils.replace(roleXml,
                        "@" + cmsRepositoryId + "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore,
                        "@" + idOfTheRepositoryWhichRepresentsTheIdentityStore);
            }

            //Obtain content object
            ImportConfiguration configuration = ImportConfiguration.object().persist(PersistMode.DO_NOT_PERSIST)
                    .build();

            ContentObject roleObject = importDao.importContentObject(roleXml, configuration);

            if (roleObject == null) {
                throw new CmsException("Could not create a content object from provided source");
            }

            //fix system name
            roleObject.setSystemName(cmsRepositoryEntityUtils.fixSystemName(roleObject.getSystemName()));

            return roleObject;
        } finally {
            if (inputStream != null) {
                IOUtils.closeQuietly(inputStream);
            }
        }

    }

}

From source file:org.betaconceptframework.astroboa.test.AstroboaTestContext.java

private void deleteResource(String resourceRelativePath) throws IOException {
    Resource versionDirectory = new ClassPathResource(resourceRelativePath);

    if (versionDirectory.exists()) {
        File file = versionDirectory.getFile();

        if (file.isFile()) {
            file.delete();//ww  w  . j a v  a  2 s  .c o  m
        } else {
            FileUtils.deleteDirectory(file);
        }
    }
}

From source file:org.betaconceptframework.astroboa.test.AstroboaTestContext.java

private void touchResource(String resourceRelativePath) throws IOException {
    Resource resource = new ClassPathResource(resourceRelativePath);

    if (resource.exists()) {
        File file = resource.getFile();

        if (file.isFile()) {
            FileUtils.touch(file);/*www  .  ja  v a2s .  co m*/
        } else {
            File[] files = file.listFiles();

            if (files != null && files.length > 0) {
                for (File child : files) {
                    FileUtils.touch(child);
                }
            }
        }
    }

}

From source file:org.betaconceptframework.astroboa.test.engine.service.TaxonomyServiceTest.java

@Test
public void testImportXMLofTaxonomiesProvidedWithTheDistribution() throws IOException {
    Resource taxonomiesHomeDir = new ClassPathResource("/taxonomies");

    Assert.assertTrue(taxonomiesHomeDir.exists(),
            "Home directory of the taxonomies provided in the distribution does not exist in "
                    + taxonomiesHomeDir.getURI().toString());

    File[] taxonomyXmls = taxonomiesHomeDir.getFile().listFiles(new FilenameFilter() {

        @Override//from   w w  w .java  2 s  .c o  m
        public boolean accept(File dir, String name) {
            return name != null && name.endsWith(".xml");
        }
    });

    Assert.assertTrue(taxonomyXmls.length > 0, "Home directory of the taxonomies provided in the distribution '"
            + taxonomiesHomeDir.getURI().toString() + "' does not contain any xml file");

    for (File taxonomyXML : taxonomyXmls) {

        Taxonomy taxonomy = taxonomyService.save(FileUtils.readFileToString(taxonomyXML, "UTF-8"));
        markTaxonomyForRemoval(taxonomy);
    }

}

From source file:org.broadleafcommerce.common.config.RuntimeEnvironmentPropertiesConfigurer.java

public void afterPropertiesSet() throws IOException {
    // If no environment override has been specified, used the default environments
    if (environments == null || environments.size() == 0) {
        environments = defaultEnvironments;
    }//from  w  w  w .  j a v a  2 s .  c  om

    // Prepend the default property locations to the specified property locations (if any)
    Set<Resource> combinedLocations = new LinkedHashSet<Resource>();
    if (!CollectionUtils.isEmpty(overridableProperyLocations)) {
        combinedLocations.addAll(overridableProperyLocations);
    }

    if (!CollectionUtils.isEmpty(propertyLocations)) {
        combinedLocations.addAll(propertyLocations);
    }
    propertyLocations = combinedLocations;

    if (!environments.contains(defaultEnvironment)) {
        throw new AssertionError(
                "Default environment '" + defaultEnvironment + "' not listed in environment list");
    }

    if (keyResolver == null) {
        keyResolver = new SystemPropertyRuntimeEnvironmentKeyResolver();
    }

    String environment = determineEnvironment();
    ArrayList<Resource> allLocations = new ArrayList<Resource>();

    /* Process configuration in the following order (later files override earlier files
     * common-shared.properties
     * [environment]-shared.properties
     * common.properties
     * [environment].properties
     * -Dproperty-override-shared specified value, if any
     * -Dproperty-override specified value, if any  */
    Set<Set<Resource>> testLocations = new LinkedHashSet<Set<Resource>>();
    testLocations.add(propertyLocations);
    testLocations.add(defaultPropertyLocations);

    for (Resource resource : createBroadleafResource()) {
        if (resource.exists()) {
            allLocations.add(resource);
        }
    }

    for (Set<Resource> locations : testLocations) {
        for (Resource resource : createSharedCommonResource(locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createSharedPropertiesResource(environment, locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createCommonResource(locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }

        for (Resource resource : createPropertiesResource(environment, locations)) {
            if (resource.exists()) {
                allLocations.add(resource);
            }
        }
    }

    Resource sharedPropertyOverride = createSharedOverrideResource();
    if (sharedPropertyOverride != null) {
        allLocations.add(sharedPropertyOverride);
    }

    Resource propertyOverride = createOverrideResource();
    if (propertyOverride != null) {
        allLocations.add(propertyOverride);
    }

    Properties props = new Properties();
    for (Resource resource : allLocations) {
        if (resource.exists()) {
            // We will log source-control managed properties with trace and overrides with info
            if (((resource.equals(sharedPropertyOverride) || resource.equals(propertyOverride)))
                    || LOG.isTraceEnabled()) {
                props = new Properties(props);
                props.load(resource.getInputStream());
                for (Entry<Object, Object> entry : props.entrySet()) {
                    if (resource.equals(sharedPropertyOverride) || resource.equals(propertyOverride)) {
                        logger.support("Read " + entry.getKey() + " from " + resource.getFilename());
                    } else {
                        LOG.trace("Read " + entry.getKey() + " from " + resource.getFilename());
                    }
                }
            }
        } else {
            LOG.debug("Unable to locate resource: " + resource.getFilename());
        }
    }

    setLocations(allLocations.toArray(new Resource[] {}));
}

From source file:org.broadleafcommerce.common.resource.service.ResourceBundlingServiceImpl.java

protected void createBundleIfNeeded(final String versionedBundleName, final List<String> filePaths,
        final ResourceResolverChain resolverChain, final List<Resource> locations) {
    if (!createdBundles.containsKey(versionedBundleName)) {
        keyLockManager.executeLocked(versionedBundleName, new LockCallback() {

            @Override//from  w  ww  .  j a  va 2  s .c  o  m
            public void doInLock() {
                Resource bundleResource = createdBundles.get(versionedBundleName);
                if (bundleResource == null || !bundleResource.exists()) {
                    bundleResource = createBundle(versionedBundleName, filePaths, resolverChain, locations);
                    if (bundleResource != null) {
                        saveBundle(bundleResource);
                    }
                }
                Resource savedResource = readBundle(versionedBundleName);
                createdBundles.put(versionedBundleName, savedResource);
            }
        });
    }
}

From source file:org.broadleafcommerce.common.web.resource.AbstractGeneratedResourceHandler.java

/**
 * This method can be used to read in a resource given a path and at least one resource location
 * //w  w  w . j a v  a2 s. c o m
 * @param path
 * @param locations
 * @return the resource from the file system, classpath, etc, if it exists
 */
protected Resource getRawResource(String path, List<Resource> locations) {
    ExtensionResultHolder erh = new ExtensionResultHolder();
    extensionManager.getProxy().getOverrideResource(path, erh);
    if (erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR) != null) {
        return (Resource) erh.getContextMap().get(ResourceRequestExtensionHandler.RESOURCE_ATTR);
    }

    for (Resource location : locations) {
        try {
            Resource resource = location.createRelative(path);
            if (resource.exists() && resource.isReadable()) {
                return resource;
            }
        } catch (IOException ex) {
            LOG.debug("Failed to create relative resource - trying next resource location", ex);
        }
    }
    return null;
}

From source file:org.broadleafcommerce.common.web.resource.resolver.BroadleafCachingResourceResolver.java

@Override
protected Resource resolveResourceInternal(HttpServletRequest request, String requestPath,
        List<? extends Resource> locations, ResourceResolverChain chain) {
    if (resourceCachingEnabled) {
        Resource resource = super.resolveResourceInternal(request, requestPath, locations, chain);

        if (logger.isDebugEnabled()) {
            if (resource == null) {
                logger.debug("Cache resolver, returned a null resource " + requestPath);
            } else if (!resource.exists()) {
                logger.debug("Cache resolver, returned a resource that doesn't exist " + requestPath + " - "
                        + resource);/*w w w. j a  v a  2s.  c om*/
            }
        }
        return resource;
    } else {
        return chain.resolveResource(request, requestPath, locations);
    }
}