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.springframework.batch.admin.web.FileController.java

@RequestMapping(value = "/files/**", method = RequestMethod.GET)
public String get(HttpServletRequest request, HttpServletResponse response, ModelMap model,
        @RequestParam(defaultValue = "0") int startFile, @RequestParam(defaultValue = "20") int pageSize,
        @ModelAttribute("date") Date date, Errors errors) throws Exception {

    list(model, startFile, pageSize);//from  www  .  jav a 2  s  .  c  o  m

    String path = request.getPathInfo().substring("/files/".length());
    Resource file = fileService.getResource(path);
    if (file == null || !file.exists()) {
        errors.reject("file.download.missing", new Object[] { path },
                "File download failed for missing file at path=" + HtmlUtils.htmlEscape(path));
        return "files";
    }

    response.setContentType("application/octet-stream");
    try {
        FileCopyUtils.copy(file.getInputStream(), response.getOutputStream());
    } catch (IOException e) {
        errors.reject("file.download.failed", new Object[] { path },
                "File download failed for path=" + HtmlUtils.htmlEscape(path));
        logger.info("File download failed for path=" + path, e);
        return "files";
    }

    return null;

}

From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java

/**
 * Creates a child {@link ApplicationContext} for the job being requested based upon
 * the /META-INF/batch.xml (if exists) and the /META-INF/batch-jobs/<jobName>.xml
 * configuration and restart the job.// w  w  w . j  a va2  s .  co m
 *
 * @param executionId the database id of the job execution to be restarted.
 * @param params any job parameters to be used during the execution of this job.
 * @throws JobExecutionAlreadyCompleteException thrown if the requested job execution has
 * a status of COMPLETE
 * @throws NoSuchJobExecutionException throw if the requested job execution does not exist
 * in the repository
 * @throws JobExecutionNotMostRecentException thrown if the requested job execution is not
 * the most recent attempt for the job instance it's related to.
 * @throws JobRestartException thrown for any general errors during the job restart process
 */
@Override
public long restart(long executionId, Properties params)
        throws JobExecutionAlreadyCompleteException, NoSuchJobExecutionException,
        JobExecutionNotMostRecentException, JobRestartException, JobSecurityException {
    org.springframework.batch.core.JobExecution previousJobExecution = jobExplorer.getJobExecution(executionId);

    if (previousJobExecution == null) {
        throw new NoSuchJobExecutionException("No JobExecution found for id: [" + executionId + "]");
    } else if (previousJobExecution.getStatus().equals(BatchStatus.COMPLETED)) {
        throw new JobExecutionAlreadyCompleteException("The requested job has already completed");
    }

    List<org.springframework.batch.core.JobExecution> previousExecutions = jobExplorer
            .getJobExecutions(previousJobExecution.getJobInstance());

    for (org.springframework.batch.core.JobExecution jobExecution : previousExecutions) {
        if (jobExecution.getCreateTime().compareTo(previousJobExecution.getCreateTime()) > 0) {
            throw new JobExecutionNotMostRecentException(
                    "The requested JobExecution to restart was not the most recently run");
        }

        if (jobExecution.getStatus().equals(BatchStatus.ABANDONED)) {
            throw new JobRestartException("JobExecution ID: " + jobExecution.getId()
                    + " is abandoned and attempted to be restarted.");
        }
    }

    final String jobName = previousJobExecution.getJobInstance().getJobName();

    Properties jobRestartProperties = getJobRestartProperties(params, previousJobExecution);

    final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(jobRestartProperties);
    batchContext.setValidating(false);

    Resource batchXml = new ClassPathResource("/META-INF/batch.xml");
    Resource jobXml = new ClassPathResource(previousJobExecution.getJobConfigurationName());

    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(baseContext);

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

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

    try {
        JobParameters jobParameters = jobParametersConverter.getJobParameters(jobRestartProperties);
        jobExecution = jobRepository.createJobExecution(previousJobExecution.getJobInstance(), jobParameters,
                previousJobExecution.getJobConfigurationName());
    } catch (Exception e) {
        throw new JobRestartException(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 Job job = batchContext.getBean(Job.class);

                    if (!job.isRestartable()) {
                        throw new JobRestartException("Job " + jobName + " is not restartable");
                    }

                    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 JobRestartException(exceptionHolder.get(0));
        }
    } catch (Exception e) {
        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 JobRestartException(e);
    }

    return jobExecution.getId();
}

From source file:org.springframework.batch.core.jsr.launch.JsrJobOperator.java

/**
 * Creates a child {@link ApplicationContext} for the job being requested based upon
 * the /META-INF/batch.xml (if exists) and the /META-INF/batch-jobs/&lt;jobName&gt;.xml
 * configuration and launches the job.  Per JSR-352, calls to this method will always
 * create a new {@link JobInstance} (and related {@link JobExecution}).
 *
 * @param jobName the name of the job XML file without the .xml that is located within the
 * /META-INF/batch-jobs directory./*from w w  w. j av  a2 s.  c om*/
 * @param params any job parameters to be used during the execution of this job.
 */
@Override
public long start(String jobName, Properties params) throws JobStartException, JobSecurityException {
    final JsrXmlApplicationContext batchContext = new JsrXmlApplicationContext(params);
    batchContext.setValidating(false);

    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);

    if (baseContext != null) {
        batchContext.setParent(baseContext);
    } else {
        batchContext.getBeanFactory().registerSingleton("jobExplorer", jobExplorer);
        batchContext.getBeanFactory().registerSingleton("jobRepository", jobRepository);
        batchContext.getBeanFactory().registerSingleton("jobParametersConverter", jobParametersConverter);
        batchContext.getBeanFactory().registerSingleton("transactionManager", transactionManager);
    }

    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 Job job = batchContext.getBean(Job.class);
                    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();
}

From source file:org.springframework.batch.item.xml.StaxEventItemWriterTests.java

@Test
public void testNonExistantResource() throws Exception {
    Resource doesntExist = mock(Resource.class);
    when(doesntExist.getFile()).thenReturn(File.createTempFile("arbitrary", null));
    when(doesntExist.exists()).thenReturn(false);

    writer.setResource(doesntExist);// w ww  .j  a  v a2 s  . c  o  m

    try {
        writer.open(executionContext);
        fail();
    } catch (IllegalStateException e) {
        assertEquals("Output resource must exist", e.getMessage());
    }
}

From source file:org.springframework.batch.test.DataSourceInitializer.java

private void doExecuteScript(final Resource scriptResource) {
    if (scriptResource == null || !scriptResource.exists())
        return;/*  www  .j  av a 2  s  . c o m*/
    TransactionTemplate transactionTemplate = new TransactionTemplate(
            new DataSourceTransactionManager(dataSource));
    transactionTemplate.execute(new TransactionCallback<Void>() {

        @Override
        public Void doInTransaction(TransactionStatus status) {
            JdbcTemplate jdbcTemplate = new JdbcTemplate(dataSource);
            String[] scripts;
            try {
                scripts = StringUtils.delimitedListToStringArray(
                        stripComments(IOUtils.readLines(scriptResource.getInputStream())), ";");
            } catch (IOException e) {
                throw new BeanInitializationException("Cannot load script from [" + scriptResource + "]", e);
            }
            for (int i = 0; i < scripts.length; i++) {
                String script = scripts[i].trim();
                if (StringUtils.hasText(script)) {
                    try {
                        jdbcTemplate.execute(script);
                    } catch (DataAccessException e) {
                        if (ignoreFailedDrop && script.toLowerCase().startsWith("drop")) {
                            logger.debug("DROP script failed (ignoring): " + script);
                        } else {
                            throw e;
                        }
                    }
                }
            }
            return null;
        }

    });

}

From source file:org.springframework.beans.factory.xml.DefaultBeanDefinitionDocumentReader.java

/**
 * Parse an "import" element and load the bean definitions
 * from the given resource into the bean factory.
 *//*w w  w .  j  a v a  2 s .com*/
protected void importBeanDefinitionResource(Element ele) {
    String location = ele.getAttribute(RESOURCE_ATTRIBUTE);
    if (!StringUtils.hasText(location)) {
        getReaderContext().error("Resource location must not be empty", ele);
        return;
    }

    // Resolve system properties: e.g. "${user.dir}"
    location = getReaderContext().getEnvironment().resolveRequiredPlaceholders(location);

    Set<Resource> actualResources = new LinkedHashSet<>(4);

    // Discover whether the location is an absolute or relative URI
    boolean absoluteLocation = false;
    try {
        absoluteLocation = ResourcePatternUtils.isUrl(location) || ResourceUtils.toURI(location).isAbsolute();
    } catch (URISyntaxException ex) {
        // cannot convert to an URI, considering the location relative
        // unless it is the well-known Spring prefix "classpath*:"
    }

    // Absolute or relative?
    if (absoluteLocation) {
        try {
            int importCount = getReaderContext().getReader().loadBeanDefinitions(location, actualResources);
            if (logger.isDebugEnabled()) {
                logger.debug(
                        "Imported " + importCount + " bean definitions from URL location [" + location + "]");
            }
        } catch (BeanDefinitionStoreException ex) {
            getReaderContext().error("Failed to import bean definitions from URL location [" + location + "]",
                    ele, ex);
        }
    } else {
        // No URL -> considering resource location as relative to the current file.
        try {
            int importCount;
            Resource relativeResource = getReaderContext().getResource().createRelative(location);
            if (relativeResource.exists()) {
                importCount = getReaderContext().getReader().loadBeanDefinitions(relativeResource);
                actualResources.add(relativeResource);
            } else {
                String baseLocation = getReaderContext().getResource().getURL().toString();
                importCount = getReaderContext().getReader().loadBeanDefinitions(
                        StringUtils.applyRelativePath(baseLocation, location), actualResources);
            }
            if (logger.isDebugEnabled()) {
                logger.debug("Imported " + importCount + " bean definitions from relative location [" + location
                        + "]");
            }
        } catch (IOException ex) {
            getReaderContext().error("Failed to resolve current resource location", ele, ex);
        } catch (BeanDefinitionStoreException ex) {
            getReaderContext().error(
                    "Failed to import bean definitions from relative location [" + location + "]", ele, ex);
        }
    }
    Resource[] actResArray = actualResources.toArray(new Resource[actualResources.size()]);
    getReaderContext().fireImportProcessed(location, actResArray, extractSource(ele));
}

From source file:org.springframework.boot.autoconfigure.jdbc.DataSourceInitialization.java

private boolean runScripts(String scripts) {

    if (this.dataSource == null) {
        logger.debug("No DataSource found so not initializing");
        return false;
    }/*w  w  w  . j  a v  a2s  . c o m*/

    List<Resource> resources = getSchemaResources(scripts);

    boolean continueOnError = this.properties.isContinueOnError();
    boolean exists = false;
    ResourceDatabasePopulator populator = new ResourceDatabasePopulator();
    for (Resource resource : resources) {
        if (resource.exists()) {
            exists = true;
            populator.addScript(resource);
            populator.setContinueOnError(continueOnError);
        }
    }
    populator.setSeparator(this.properties.getSeparator());

    if (exists) {
        DatabasePopulatorUtils.execute(populator, this.dataSource);
    }

    return exists;

}

From source file:org.springframework.boot.autoconfigure.jdbc.DataSourceInitializer.java

private List<Resource> getResources(String locations) {
    List<Resource> resources = new ArrayList<Resource>();
    for (String location : StringUtils.commaDelimitedListToStringArray(locations)) {
        try {/*from w w w . ja va  2 s.  c o m*/
            for (Resource resource : this.applicationContext.getResources(location)) {
                if (resource.exists()) {
                    resources.add(resource);
                }
            }
        } catch (IOException ex) {
            throw new IllegalStateException("Unable to load resource from " + location, ex);
        }
    }
    return resources;
}

From source file:org.springframework.boot.autoconfigure.web.reactive.error.AbstractErrorWebExceptionHandler.java

private Resource resolveResource(String viewName) {
    for (String location : this.resourceProperties.getStaticLocations()) {
        try {/* w  ww .  j a v a2s  .c o  m*/
            Resource resource = this.applicationContext.getResource(location);
            resource = resource.createRelative(viewName + ".html");
            if (resource.exists()) {
                return resource;
            }
        } catch (Exception ex) {
            // Ignore
        }
    }
    return null;
}

From source file:org.springframework.boot.env.PropertySourcesLoader.java

private boolean isFile(Resource resource) {
    return resource != null && resource.exists()
            && StringUtils.hasText(StringUtils.getFilenameExtension(resource.getFilename()));
}