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.codehaus.groovy.grails.scaffolding.AbstractGrailsTemplateGenerator.java

protected Set<String> getTemplateNames() throws IOException {

    if (resourceLoader != null && grailsApplication.isWarDeployed()) {
        try {//w  w w  .  j  a va 2  s.  c  o  m
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(
                    resourceLoader);
            return extractNames(resolver.getResources("/WEB-INF/templates/scaffolding/*.gsp"));
        } catch (Exception e) {
            return Collections.emptySet();
        }
    }

    PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
    Set<String> resources = new HashSet<String>();

    String templatesDirPath = basedir + "/src/templates/scaffolding";
    Resource templatesDir = new FileSystemResource(templatesDirPath);
    if (templatesDir.exists()) {
        try {
            resources.addAll(extractNames(resolver.getResources("file:" + templatesDirPath + "/*.gsp")));
        } catch (Exception e) {
            log.error("Error while loading views from " + basedir, e);
        }
    }

    File pluginDir = getPluginDir();
    try {
        resources.addAll(
                extractNames(resolver.getResources("file:" + pluginDir + "/src/templates/scaffolding/*.gsp")));
    } catch (Exception e) {
        // ignore
        log.error("Error locating templates from " + pluginDir + ": " + e.getMessage(), e);
    }

    return resources;
}

From source file:org.alfresco.ibatis.HierarchicalXMLConfigBuilder.java

private void mapperElement(XNode parent) throws Exception {
    if (parent != null) {
        for (XNode child : parent.getChildren()) {
            if ("package".equals(child.getName())) {
                String mapperPackage = child.getStringAttribute("name");
                configuration.addMappers(mapperPackage);
            } else {
                String resource = child.getStringAttribute("resource");
                String url = child.getStringAttribute("url");
                String mapperClass = child.getStringAttribute("class");
                if (resource != null && url == null && mapperClass == null) {
                    ErrorContext.instance().resource(resource);

                    // // EXTENDED
                    // inputStream = Resources.getResourceAsStream(resource);
                    InputStream inputStream = null;
                    Resource res = resourceLoader.getResource(resource);
                    if (res != null && res.exists()) {
                        inputStream = res.getInputStream();
                    } else {
                        throw new BuilderException("Failed to get resource: " + resource);
                    }/*from w ww .  j av  a 2s.  c o m*/

                    //InputStream inputStream = Resources.getResourceAsStream(resource);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, resource,
                            configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url != null && mapperClass == null) {
                    ErrorContext.instance().resource(url);
                    InputStream inputStream = Resources.getUrlAsStream(url);
                    XMLMapperBuilder mapperParser = new XMLMapperBuilder(inputStream, configuration, url,
                            configuration.getSqlFragments());
                    mapperParser.parse();
                } else if (resource == null && url == null && mapperClass != null) {
                    Class<?> mapperInterface = Resources.classForName(mapperClass);
                    configuration.addMapper(mapperInterface);
                } else {
                    throw new BuilderException(
                            "A mapper element may only specify a url, resource or class, but not more than one.");
                }
            }
        }
    }
}

From source file:com.alibaba.citrus.service.velocity.impl.VelocityConfigurationImpl.java

private void addMacroResources(String path, Resource[] resources) {
    if (resources != null) {
        // vector?VelocimacroFactory???
        @SuppressWarnings("unchecked")
        Set<String> macros = createHashSet(properties.getVector(VM_LIBRARY));

        for (Resource resource : resources) {
            if (resource.exists()) {
                String templateName = null;

                // resourceServletResourceResourceAdapter??resourceName
                if (path != null && resource instanceof ContextResource) {
                    String resourceName = ((ContextResource) resource).getPathWithinContext();

                    if (resourceName.startsWith(path)) {
                        templateName = resourceName.substring(path.length());
                    }/* ww  w.j  a  va2s  .  c  om*/
                }

                // ???resourceName
                if (templateName == null) {
                    templateName = getTemplateNameOfPreloadedResource(resource);
                }

                if (!macros.contains(templateName)) {
                    properties.addProperty(VM_LIBRARY, templateName);
                    macros.add(templateName);
                }
            }
        }
    }
}

From source file:com.google.api.ads.adwords.awreporting.server.rest.RestServer.java

/**
 * Initialize the application context, adding the properties configuration file depending on the
 * specified path./* w w  w.  j a  v a  2s .c o m*/
 * @throws IOException 
 */
public void initApplicationContextAndProperties(String propertiesFilePath) throws IOException {

    Resource resource = new ClassPathResource(propertiesFilePath);
    if (!resource.exists()) {
        resource = new FileSystemResource(propertiesFilePath);
    }
    DynamicPropertyPlaceholderConfigurer.setDynamicResource(resource);
    properties = PropertiesLoaderUtils.loadProperties(resource);

    // Set the server port from the properties file or use 8081 as default. 
    String strServerPort = properties.getProperty("serverport");
    if (strServerPort != null && strServerPort.length() > 0) {
        serverPort = Integer.valueOf(strServerPort);
    }

    listOfClassPathXml.add("classpath:storage-helper-beans.xml");

    listOfClassPathXml.add("classpath:kratu-processor-beans.xml");

    listOfClassPathXml.add("aw-reporting-server-webauthenticator.xml");

    listOfClassPathXml.add("aw-pdf-exporter-beans.xml");

    // Choose the DB type to use based properties file
    String dbType = (String) properties.get(AW_REPORT_MODEL_DB_TYPE);
    if (dbType != null && dbType.equals(DataBaseType.MONGODB.name())) {
        logger.info("Using MONGO DB configuration properties.");
        listOfClassPathXml.add("classpath:aw-report-mongodb-beans.xml");
    } else {
        logger.info("Using SQL DB configuration properties.");
        listOfClassPathXml.add("classpath:aw-report-sql-beans.xml");
    }

    // Choose the Processor type to use based properties file
    String processorType = (String) properties.get(AW_REPORT_PROCESSOR_TYPE);
    if (processorType != null && processorType.equals(ProcessorType.ONMEMORY.name())) {
        logger.info("Using ONMEMORY Processor.");
        listOfClassPathXml.add("classpath:aw-report-processor-beans-onmemory.xml");
    } else {
        logger.info("Using ONFILE Processor.");
        listOfClassPathXml.add("classpath:aw-report-processor-beans-onfile.xml");
    }

    appCtx = new ClassPathXmlApplicationContext(
            listOfClassPathXml.toArray(new String[listOfClassPathXml.size()]));
    persister = appCtx.getBean(EntityPersister.class);
    storageHelper = appCtx.getBean(StorageHelper.class);
    webAuthenticator = appCtx.getBean(WebAuthenticator.class);
}

From source file:org.powertac.samplebroker.core.BrokerPropertiesService.java

private boolean validXmlResource(Resource xml) {
    try {/*from w  w  w  .  j a v  a 2 s.com*/
        log.info("Validating resource " + xml.getURI());
        String path = xml.getURI().toString();
        for (String regex : excludedPaths) {
            if (path.matches(regex)) {
                return false;
            }
            if (!xml.exists()) {
                log.warn("Resource " + xml.getURI() + " does not exist");
                return false;
            }
            if (!xml.isReadable()) {
                log.warn("Resource " + xml.getURI() + " is not readable");
                return false;
            }
        }
        return true;
    } catch (IOException e) {
        log.error("Should not happen: " + e.toString());
        return false;
    } catch (Exception e) {
        log.error("Validation error " + e.toString());
        e.printStackTrace();
        return false;
    }
}

From source file:com.myee.tarot.core.config.RuntimePropertyPlaceholderConfigurer.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  av a  2s  . 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 RuntimePropertyEnvironmentKeyResolver();
    }

    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:com.adaptc.mws.plugins.testing.transformations.TestForTransformation.java

public Resource findResourceForClassName(String className) {
    if (className.contains(CLOSURE_MARKER)) {
        className = className.substring(0, className.indexOf(CLOSURE_MARKER));
    }/*w  ww .j  ava  2s . c o m*/
    String classNameWithPathSeparator = className.replace(".", FILE_SEPARATOR);
    Resource resource = null;
    for (String pathPattern : getSearchPatternForExtension(classNameWithPathSeparator, ".groovy", ".java")) {
        resource = resolvePathToResource(pathPattern);
        if (resource != null && resource.exists()) {
            break;
        }
    }
    return resource != null && resource.exists() ? resource : null;
}

From source file:com.netflix.genie.web.tasks.node.DiskCleanupTask.java

/**
 * Constructor. Schedules this task to be run by the task scheduler.
 *
 * @param properties       The disk cleanup properties to use.
 * @param scheduler        The scheduler to use to schedule the cron trigger.
 * @param jobsDir          The resource representing the location of the job directory
 * @param jobSearchService The service to find jobs with
 * @param jobsProperties   The jobs properties to use
 * @param processExecutor  The process executor to use to delete directories
 * @param registry         The metrics registry
 * @throws IOException When it is unable to open a file reference to the job directory
 *//*from w  w w .j  av  a  2s . co  m*/
@Autowired
public DiskCleanupTask(@NotNull final DiskCleanupProperties properties, @NotNull final TaskScheduler scheduler,
        @NotNull final Resource jobsDir, @NotNull final JobSearchService jobSearchService,
        @NotNull final JobsProperties jobsProperties, @NotNull final Executor processExecutor,
        @NotNull final Registry registry) throws IOException {
    // Job Directory is guaranteed to exist by the MvcConfig bean creation but just in case someone overrides
    if (!jobsDir.exists()) {
        throw new IOException("Jobs dir " + jobsDir + " doesn't exist. Unable to create task to cleanup.");
    }

    this.properties = properties;
    this.jobsDir = jobsDir.getFile();
    this.jobSearchService = jobSearchService;
    this.runAsUser = jobsProperties.getUsers().isRunAsUserEnabled();
    this.processExecutor = processExecutor;

    this.numberOfDeletedJobDirs = registry.gauge("genie.tasks.diskCleanup.numberDeletedJobDirs.gauge",
            new AtomicLong());
    this.numberOfDirsUnableToDelete = registry.gauge("genie.tasks.diskCleanup.numberDirsUnableToDelete.gauge",
            new AtomicLong());
    this.unableToGetJobCounter = registry.counter("genie.tasks.diskCleanup.unableToGetJobs.rate");
    this.unableToDeleteJobDirCounter = registry.counter("genie.tasks.diskCleanup.unableToDeleteJobsDir.rate");

    // Only schedule the task if we don't need sudo while on a non-unix system
    if (this.runAsUser && !SystemUtils.IS_OS_UNIX) {
        log.error("System is not UNIX like. Unable to schedule disk cleanup due to needing Unix commands");
    } else {
        final CronTrigger trigger = new CronTrigger(properties.getExpression(), JobConstants.UTC);
        scheduler.schedule(this, trigger);
    }
}

From source file:de.codecentric.batch.jsr352.CustomJsrJobOperator.java

@Override
public long start(String jobName, Properties params) throws JobStartException, JobSecurityException {
    final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params);
    batchContext.setValidating(false);//from w  w w.  j  a  v a  2 s .co  m

    Resource batchXml = new ClassPathResource("/META-INF/batch.xml");
    String jobConfigurationLocation = "/META-INF/batch-jobs/" + jobName + ".xml";
    Resource jobXml = new ClassPathResource(jobConfigurationLocation);

    if (batchXml.exists()) {
        batchContext.load(batchXml);
    }

    if (jobXml.exists()) {
        batchContext.load(jobXml);
    }

    AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder
            .genericBeanDefinition("org.springframework.batch.core.jsr.JsrJobContextFactoryBean")
            .getBeanDefinition();
    beanDefinition.setScope(BeanDefinition.SCOPE_SINGLETON);
    batchContext.registerBeanDefinition(JSR_JOB_CONTEXT_BEAN_NAME, beanDefinition);

    batchContext.setParent(parentContext);

    try {
        batchContext.refresh();
    } catch (BeanCreationException e) {
        throw new JobStartException(e);
    }

    Assert.notNull(jobName, "The job name must not be null.");

    final org.springframework.batch.core.JobExecution jobExecution;

    try {
        JobParameters jobParameters = jobParametersConverter.getJobParameters(params);
        String[] jobNames = batchContext.getBeanNamesForType(Job.class);

        if (jobNames == null || jobNames.length <= 0) {
            throw new BatchRuntimeException("No Job defined in current context");
        }

        org.springframework.batch.core.JobInstance jobInstance = jobRepository.createJobInstance(jobNames[0],
                jobParameters);
        jobExecution = jobRepository.createJobExecution(jobInstance, jobParameters, jobConfigurationLocation);
    } catch (Exception e) {
        throw new JobStartException(e);
    }

    try {
        final Semaphore semaphore = new Semaphore(1);
        final List<Exception> exceptionHolder = Collections.synchronizedList(new ArrayList<Exception>());
        semaphore.acquire();

        taskExecutor.execute(new Runnable() {

            @Override
            public void run() {
                JsrJobContextFactoryBean factoryBean = null;
                try {
                    factoryBean = (JsrJobContextFactoryBean) batchContext
                            .getBean("&" + JSR_JOB_CONTEXT_BEAN_NAME);
                    factoryBean.setJobExecution(jobExecution);
                    final AbstractJob job = batchContext.getBean(AbstractJob.class);
                    addListenerToJobService.addListenerToJob(job);
                    semaphore.release();
                    // Initialization of the JobExecution for job level dependencies
                    jobRegistry.register(job, jobExecution);
                    job.execute(jobExecution);
                    jobRegistry.remove(jobExecution);
                } catch (Exception e) {
                    exceptionHolder.add(e);
                } finally {
                    if (factoryBean != null) {
                        factoryBean.close();
                    }

                    batchContext.close();

                    if (semaphore.availablePermits() == 0) {
                        semaphore.release();
                    }
                }
            }
        });

        semaphore.acquire();
        if (exceptionHolder.size() > 0) {
            semaphore.release();
            throw new JobStartException(exceptionHolder.get(0));
        }
    } catch (Exception e) {
        if (jobRegistry.exists(jobExecution.getId())) {
            jobRegistry.remove(jobExecution);
        }
        jobExecution.upgradeStatus(BatchStatus.FAILED);
        if (jobExecution.getExitStatus().equals(ExitStatus.UNKNOWN)) {
            jobExecution.setExitStatus(ExitStatus.FAILED.addExitDescription(e));
        }
        jobRepository.update(jobExecution);

        if (batchContext.isActive()) {
            batchContext.close();
        }

        throw new JobStartException(e);
    }
    return jobExecution.getId();
}