Example usage for org.springframework.util Assert state

List of usage examples for org.springframework.util Assert state

Introduction

In this page you can find the example usage for org.springframework.util Assert state.

Prototype

public static void state(boolean expression, Supplier<String> messageSupplier) 

Source Link

Document

Assert a boolean expression, throwing an IllegalStateException if the expression evaluates to false .

Usage

From source file:org.springframework.batch.admin.service.LocalFileService.java

public FileInfo createFile(String path) throws IOException {

    path = sanitize(path);/* ww w  .  j a v  a  2  s .co m*/

    Assert.hasText(path, "The file path must not be empty");

    String name = path.substring(path.lastIndexOf("/") + 1);
    String parent = path.substring(0, path.lastIndexOf(name));
    if (parent.endsWith("/")) {
        parent = parent.substring(0, parent.length() - 1);
    }

    File directory = new File(outputDir, parent);
    directory.mkdirs();
    Assert.state(directory.exists() && directory.isDirectory(), "Could not create directory: " + directory);

    FileInfo result = new FileInfo(path);
    File dest = new File(outputDir, result.getFileName());
    dest.createNewFile();

    return result;

}

From source file:org.springframework.batch.core.configuration.xml.StepParserStepFactoryBean.java

private void configurePartitionStep(PartitionStep ts) {
    Assert.state(partitioner != null, "A Partitioner must be provided for a partition step");
    configureAbstractStep(ts);//from   w  w  w  .j a  v a  2s .  co  m

    if (partitionHandler != null) {
        ts.setPartitionHandler(partitionHandler);
    } else {
        TaskExecutorPartitionHandler partitionHandler = new TaskExecutorPartitionHandler();
        partitionHandler.setStep(step);
        if (taskExecutor == null) {
            taskExecutor = new SyncTaskExecutor();
        }
        partitionHandler.setGridSize(gridSize);
        partitionHandler.setTaskExecutor(taskExecutor);
        ts.setPartitionHandler(partitionHandler);
    }

    boolean allowStartIfComplete = this.allowStartIfComplete != null ? this.allowStartIfComplete : false;
    String name = this.name;
    if (step != null) {
        try {
            allowStartIfComplete = step.isAllowStartIfComplete();
            name = step.getName();
        } catch (Exception e) {
            logger.info("Ignored exception from step asking for name and allowStartIfComplete flag. "
                    + "Using default from enclosing PartitionStep (" + name + "," + allowStartIfComplete
                    + ").");
        }
    }
    SimpleStepExecutionSplitter splitter = new SimpleStepExecutionSplitter(jobRepository, allowStartIfComplete,
            name, partitioner);
    ts.setStepExecutionSplitter(splitter);
    if (stepExecutionAggregator != null) {
        ts.setStepExecutionAggregator(stepExecutionAggregator);
    }
}

From source file:org.springframework.batch.core.job.SimpleStepHandler.java

/**
 * Check mandatory properties (jobRepository).
 *
 * @see InitializingBean#afterPropertiesSet()
 *///  ww w.  j ava 2 s.c o  m
@Override
public void afterPropertiesSet() throws Exception {
    Assert.state(jobRepository != null, "A JobRepository must be provided");
}

From source file:org.springframework.batch.core.jsr.job.DefaultStepHandler.java

@Override
public void afterPropertiesSet() throws Exception {
    super.afterPropertiesSet();
    Assert.state(jobExplorer != null, "A JobExplorer must be provided");
}

From source file:org.springframework.batch.core.launch.support.CommandLineJobRunner.java

@SuppressWarnings("resource")
int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {/*from  ww  w  . j a  va  2s .co m*/
        try {
            context = new AnnotationConfigApplicationContext(Class.forName(jobPath));
        } catch (ClassNotFoundException cnfe) {
            context = new ClassPathXmlApplicationContext(jobPath);
        }

        context.getAutowireCapableBeanFactory().autowireBeanProperties(this,
                AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE, false);

        Assert.state(launcher != null, "A JobLauncher must be provided.  Please add one to the configuration.");
        if (opts.contains("-restart") || opts.contains("-next")) {
            Assert.state(jobExplorer != null,
                    "A JobExplorer must be provided for a restart or start next operation.  Please add one to the configuration.");
        }

        String jobName = jobIdentifier;

        JobParameters jobParameters = jobParametersConverter
                .getJobParameters(StringUtils.splitArrayElementsIntoProperties(parameters, "="));
        Assert.isTrue(parameters == null || parameters.length == 0 || !jobParameters.isEmpty(),
                "Invalid JobParameters " + Arrays.asList(parameters)
                        + ". If parameters are provided they should be in the form name=value (no whitespace).");

        if (opts.contains("-stop")) {
            List<JobExecution> jobExecutions = getRunningJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotRunningException(
                        "No running execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.STOPPING);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        if (opts.contains("-abandon")) {
            List<JobExecution> jobExecutions = getStoppedJobExecutions(jobIdentifier);
            if (jobExecutions == null) {
                throw new JobExecutionNotStoppedException(
                        "No stopped execution found for job=" + jobIdentifier);
            }
            for (JobExecution jobExecution : jobExecutions) {
                jobExecution.setStatus(BatchStatus.ABANDONED);
                jobRepository.update(jobExecution);
            }
            return exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode());
        }

        if (opts.contains("-restart")) {
            JobExecution jobExecution = getLastFailedJobExecution(jobIdentifier);
            if (jobExecution == null) {
                throw new JobExecutionNotFailedException(
                        "No failed or stopped execution found for job=" + jobIdentifier);
            }
            jobParameters = jobExecution.getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job = null;
        if (jobLocator != null) {
            try {
                job = jobLocator.getJob(jobName);
            } catch (NoSuchJobException e) {
            }
        }
        if (job == null) {
            job = (Job) context.getBean(jobName);
        }

        if (opts.contains("-next")) {
            JobParameters nextParameters = getNextJobParameters(job);
            Map<String, JobParameter> map = new HashMap<String, JobParameter>(nextParameters.getParameters());
            map.putAll(jobParameters.getParameters());
            jobParameters = new JobParameters(map);
        }

        JobExecution jobExecution = launcher.run(job, jobParameters);
        return exitCodeMapper.intValue(jobExecution.getExitStatus().getExitCode());

    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        logger.error(message, e);
        CommandLineJobRunner.message = message;
        return exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode());
    } finally {
        if (context != null) {
            context.close();
        }
    }
}

From source file:org.springframework.batch.core.launch.support.JobRegistryBackgroundJobRunner.java

/**
 * Supply a list of application context locations, starting with the parent
 * context, and followed by the children. The parent must contain a
 * {@link JobRegistry} and the child contexts are expected to contain
 * {@link Job} definitions, each of which will be registered wit the
 * registry.//w  w  w. j a v a 2 s .  c om
 *
 * Example usage:
 *
 * <pre>
 * $ java -classpath ... JobRegistryBackgroundJobRunner job-registry-context.xml job1.xml job2.xml ...
 * </pre>
 *
 * The child contexts are created only when needed though the
 * {@link JobFactory} interface (but the XML is validated on startup by
 * using it to create a {@link BeanFactory} which is then discarded).
 *
 * The parent context is created in a separate thread, and the program will
 * pause for input in an infinite loop until the user hits any key.
 *
 * @param args the context locations to use (first one is for parent)
 * @throws Exception if anything goes wrong with the context creation
 */
public static void main(String... args) throws Exception {

    Assert.state(args.length >= 1, "At least one argument (the parent context path) must be provided.");

    final JobRegistryBackgroundJobRunner launcher = new JobRegistryBackgroundJobRunner(args[0]);
    errors.clear();

    logger.info("Starting job registry in parent context from XML at: [" + args[0] + "]");

    new Thread(new Runnable() {
        @Override
        public void run() {
            try {
                launcher.run();
            } catch (RuntimeException e) {
                errors.add(e);
                throw e;
            }
        }
    }).start();

    logger.info("Waiting for parent context to start.");
    while (launcher.parentContext == null && errors.isEmpty()) {
        Thread.sleep(100L);
    }

    synchronized (errors) {
        if (!errors.isEmpty()) {
            logger.info(errors.size() + " errors detected on startup of parent context.  Rethrowing.");
            throw errors.get(0);
        }
    }
    errors.clear();

    // Paths to individual job configurations.
    final String[] paths = new String[args.length - 1];
    System.arraycopy(args, 1, paths, 0, paths.length);

    logger.info("Parent context started.  Registering jobs from paths: " + Arrays.asList(paths));
    launcher.register(paths);

    if (System.getProperty(EMBEDDED) != null) {
        launcher.destroy();
        return;
    }

    synchronized (JobRegistryBackgroundJobRunner.class) {
        System.out.println(
                "Started application.  Interrupt (CTRL-C) or call JobRegistryBackgroundJobRunner.stop() to exit.");
        JobRegistryBackgroundJobRunner.class.wait();
    }
    launcher.destroy();

}

From source file:org.springframework.batch.core.launch.support.SimpleJobLauncher.java

/**
 * Ensure the required dependencies of a {@link JobRepository} have been
 * set./* w  w  w  . ja v  a2 s.  com*/
 */
@Override
public void afterPropertiesSet() throws Exception {
    Assert.state(jobRepository != null, "A JobRepository has not been set.");
    if (taskExecutor == null) {
        logger.info("No TaskExecutor has been set, defaulting to synchronous executor.");
        taskExecutor = new SyncTaskExecutor();
    }
}

From source file:org.springframework.batch.core.partition.gemfire.RemoteScope.java

public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {

    beanFactory.registerScope(name, this);

    this.beanFactory = beanFactory;
    evaluationContext = new StandardEvaluationContext();
    evaluationContext.addPropertyAccessor(new BeanFactoryAccessor());

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a BeanDefinitionRegistry, so RefreshScope cannot be used.");
    BeanDefinitionRegistry registry = (BeanDefinitionRegistry) beanFactory;

    String id = this.id;
    if (id == null) {
        String names = Arrays.asList(registry.getBeanDefinitionNames()).toString();
        logger.debug("Generating bean factory id from names: " + names);
        id = UUID.nameUUIDFromBytes(names.getBytes()).toString();
        logger.debug("Generated bean factory id: " + id);
    }//from  ww  w  . j a v a  2s  .  c  o  m

    Assert.state(beanFactory instanceof BeanDefinitionRegistry,
            "BeanFactory was not a DefaultListableBeanFactory, so RefreshScope cannot be used.");
    ((DefaultListableBeanFactory) beanFactory).setSerializationId(id);

    for (String beanName : beanFactory.getBeanDefinitionNames()) {
        BeanDefinition definition = beanFactory.getBeanDefinition(beanName);
        // Replace this or any of its inner beans with scoped proxy if it
        // has this scope
        boolean scoped = name.equals(definition.getScope());
        Scopifier scopifier = new Scopifier(registry, name, proxyTargetClass, scoped);
        scopifier.visitBeanDefinition(definition);
        if (scoped) {
            createScopedProxy(beanName, definition, registry, proxyTargetClass);
        }
    }

}

From source file:org.springframework.batch.core.repository.dao.JdbcJobExecutionDao.java

@Override
public JobExecution getLastJobExecution(JobInstance jobInstance) {

    Long id = jobInstance.getId();

    List<JobExecution> executions = getJdbcTemplate().query(getQuery(GET_LAST_EXECUTION),
            new JobExecutionRowMapper(jobInstance), id, id);

    Assert.state(executions.size() <= 1, "There must be at most one latest job execution");

    if (executions.isEmpty()) {
        return null;
    } else {//w  w  w .  j  a  va2 s .  co  m
        return executions.get(0);
    }
}

From source file:org.springframework.batch.core.repository.dao.JdbcStepExecutionDao.java

@Override
public StepExecution getStepExecution(JobExecution jobExecution, Long stepExecutionId) {
    List<StepExecution> executions = getJdbcTemplate().query(getQuery(GET_STEP_EXECUTION),
            new StepExecutionRowMapper(jobExecution), jobExecution.getId(), stepExecutionId);

    Assert.state(executions.size() <= 1,
            "There can be at most one step execution with given name for single job execution");
    if (executions.isEmpty()) {
        return null;
    } else {//from w  w w. j  a va 2  s.  com
        return executions.get(0);
    }
}