Example usage for org.springframework.batch.core JobExecution getEndTime

List of usage examples for org.springframework.batch.core JobExecution getEndTime

Introduction

In this page you can find the example usage for org.springframework.batch.core JobExecution getEndTime.

Prototype

public Date getEndTime() 

Source Link

Usage

From source file:lcn.module.batch.core.launch.support.CommandLineRunner.java

/**
 * Batch Job? ./*from  w  w  w  .j  a  v  a 2  s  .  co  m*/
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        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.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        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.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        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).");

        // Batch Job? .
        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());
        }

        // ? Batch Job? ? abandon .
        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());
        }

        // Batch Job? .
        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.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        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);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("CommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

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

From source file:egovframework.rte.bat.core.launch.support.EgovCommandLineRunner.java

/**
 * Batch Job? .//from  ww  w .j a v  a  2  s  . com
 * ?  , Job ? / JobExecutionID, Job Parameter
 *  CommandLineRunner Option ? .
 * 
 * @param jobPath : Job Context ? XML ?  
 * @param jobIdentifier : Job ? /JobExecutionID
 * @param parameters : Job Parameter 
 * @param opts : CommandLineRunner (-restart, -next, -stop, -abandon)
 */
public int start(String jobPath, String jobIdentifier, String[] parameters, Set<String> opts) {

    ConfigurableApplicationContext context = null;

    try {
        //  ApplicationContext ?.
        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.");
        // ? Batch Job? , ? Batch Job?  ? JobExplorer  ?.
        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.");
        }

        // Job? ?? .
        String jobName = jobIdentifier;

        // JobParameters ?.
        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).");

        // Batch Job? .
        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());
        }

        // ? Batch Job? ? abandon .
        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());
        }

        // Batch Job? .
        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.getJobInstance().getJobParameters();
            jobName = jobExecution.getJobInstance().getJobName();
        }

        Job job;

        // JobLocator  Job?  null? ApplicationContext? Job? .
        if (jobLocator != null) {
            job = jobLocator.getJob(jobName);
        } else {
            job = (Job) context.getBean(jobName);
        }

        // ? Batch Job?   Job Parameters ?.
        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);
        }

        // Batch Job? .
        JobExecution jobExecution = launcher.run(job, jobParameters);
        logger.warn("EgovCommandLineRunner's Job Information");
        logger.warn("jobName=" + jobExecution.getJobInstance().getJobName());
        logger.warn("jobParamters=" + jobParameters.toString());
        logger.warn("jobExecutionTime="
                + (jobExecution.getEndTime().getTime() - jobExecution.getStartTime().getTime()) / 1000f + "s");

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

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

/**
 *
 * SQL implementation using Sequences via the Spring incrementer
 * abstraction. Once a new id has been obtained, the JobExecution is saved
 * via a SQL INSERT statement./*from ww w  .  j  a v a  2s .c o m*/
 *
 * @see JobExecutionDao#saveJobExecution(JobExecution)
 * @throws IllegalArgumentException if jobExecution is null, as well as any
 * of it's fields to be persisted.
 */
@Override
public void saveJobExecution(JobExecution jobExecution) {

    validateJobExecution(jobExecution);

    jobExecution.incrementVersion();

    jobExecution.setId(jobExecutionIncrementer.nextLongValue());
    Object[] parameters = new Object[] { jobExecution.getId(), jobExecution.getJobId(),
            jobExecution.getStartTime(), jobExecution.getEndTime(), jobExecution.getStatus().toString(),
            jobExecution.getExitStatus().getExitCode(), jobExecution.getExitStatus().getExitDescription(),
            jobExecution.getVersion(), jobExecution.getCreateTime(), jobExecution.getLastUpdated(),
            jobExecution.getJobConfigurationName() };
    getJdbcTemplate().update(getQuery(SAVE_JOB_EXECUTION), parameters,
            new int[] { Types.BIGINT, Types.BIGINT, Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR,
                    Types.VARCHAR, Types.VARCHAR, Types.INTEGER, Types.TIMESTAMP, Types.TIMESTAMP,
                    Types.VARCHAR });

    insertJobParameters(jobExecution.getId(), jobExecution.getJobParameters());
}

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

/**
 * Update given JobExecution using a SQL UPDATE statement. The JobExecution
 * is first checked to ensure all fields are not null, and that it has an
 * ID. The database is then queried to ensure that the ID exists, which
 * ensures that it is valid./*w  w  w  .  j  a v a 2s . c  o m*/
 *
 * @see JobExecutionDao#updateJobExecution(JobExecution)
 */
@Override
public void updateJobExecution(JobExecution jobExecution) {

    validateJobExecution(jobExecution);

    Assert.notNull(jobExecution.getId(),
            "JobExecution ID cannot be null. JobExecution must be saved before it can be updated");

    Assert.notNull(jobExecution.getVersion(),
            "JobExecution version cannot be null. JobExecution must be saved before it can be updated");

    synchronized (jobExecution) {
        Integer version = jobExecution.getVersion() + 1;

        String exitDescription = jobExecution.getExitStatus().getExitDescription();
        if (exitDescription != null && exitDescription.length() > exitMessageLength) {
            exitDescription = exitDescription.substring(0, exitMessageLength);
            if (logger.isDebugEnabled()) {
                logger.debug("Truncating long message before update of JobExecution: " + jobExecution);
            }
        }
        Object[] parameters = new Object[] { jobExecution.getStartTime(), jobExecution.getEndTime(),
                jobExecution.getStatus().toString(), jobExecution.getExitStatus().getExitCode(),
                exitDescription, version, jobExecution.getCreateTime(), jobExecution.getLastUpdated(),
                jobExecution.getId(), jobExecution.getVersion() };

        // Check if given JobExecution's Id already exists, if none is found
        // it
        // is invalid and
        // an exception should be thrown.
        if (getJdbcTemplate().queryForObject(getQuery(CHECK_JOB_EXECUTION_EXISTS), Integer.class,
                new Object[] { jobExecution.getId() }) != 1) {
            throw new NoSuchObjectException("Invalid JobExecution, ID " + jobExecution.getId() + " not found.");
        }

        int count = getJdbcTemplate().update(getQuery(UPDATE_JOB_EXECUTION), parameters,
                new int[] { Types.TIMESTAMP, Types.TIMESTAMP, Types.VARCHAR, Types.VARCHAR, Types.VARCHAR,
                        Types.INTEGER, Types.TIMESTAMP, Types.TIMESTAMP, Types.BIGINT, Types.INTEGER });

        // Avoid concurrent modifications...
        if (count == 0) {
            int curentVersion = getJdbcTemplate().queryForObject(getQuery(CURRENT_VERSION_JOB_EXECUTION),
                    Integer.class, new Object[] { jobExecution.getId() });
            throw new OptimisticLockingFailureException(
                    "Attempt to update job execution id=" + jobExecution.getId() + " with wrong version ("
                            + jobExecution.getVersion() + "), where current version is " + curentVersion);
        }

        jobExecution.incrementVersion();
    }
}

From source file:org.springframework.batch.integration.x.IncrementalColumnRangePartitioner.java

@Override
public void beforeStep(StepExecution stepExecution) {
    if (StringUtils.hasText(checkColumn)) {

        if (overrideValue != null && overrideValue >= 0) {
            this.incrementalMin = overrideValue;
        } else {//  ww  w  .j a va2 s. c o  m
            String jobName = stepExecution.getJobExecution().getJobInstance().getJobName();

            // Get the last jobInstance...not the current one
            List<JobInstance> jobInstances = jobExplorer.getJobInstances(jobName, 1, 1);

            if (jobInstances.size() > 0) {
                JobInstance lastInstance = jobInstances.get(jobInstances.size() - 1);

                List<JobExecution> executions = jobExplorer.getJobExecutions(lastInstance);

                JobExecution lastExecution = executions.get(0);

                for (JobExecution execution : executions) {
                    if (lastExecution.getEndTime().getTime() < execution.getEndTime().getTime()) {
                        lastExecution = execution;
                    }
                }

                if (lastExecution.getExecutionContext().containsKey(BATCH_INCREMENTAL_MAX_ID)) {
                    this.incrementalMin = lastExecution.getExecutionContext().getLong(BATCH_INCREMENTAL_MAX_ID);
                } else {
                    this.incrementalMin = Long.MIN_VALUE;
                }
            } else {
                this.incrementalMin = Long.MIN_VALUE;
            }
        }

        long newMin = jdbcTemplate.queryForObject(String.format("select max(%s) from %s", checkColumn, table),
                Integer.class);

        stepExecution.getExecutionContext().put(BATCH_INCREMENTAL_MAX_ID, newMin);
    }

    if (StringUtils.hasText(column) && StringUtils.hasText(table)) {
        if (StringUtils.hasText(checkColumn)) {
            Long minResult = jdbcTemplate.queryForObject("SELECT MIN(" + column + ") from " + table + " where "
                    + checkColumn + " > " + this.incrementalMin, Long.class);
            Long maxResult = jdbcTemplate.queryForObject("SELECT MAX(" + column + ") from " + table + " where "
                    + checkColumn + " > " + this.incrementalMin, Long.class);
            this.partitionMin = minResult != null ? minResult : Long.MIN_VALUE;
            this.partitionMax = maxResult != null ? maxResult : Long.MAX_VALUE;
        } else {
            Long minResult = jdbcTemplate.queryForObject("SELECT MIN(" + column + ") from " + table,
                    Long.class);
            Long maxResult = jdbcTemplate.queryForObject("SELECT MAX(" + column + ") from " + table,
                    Long.class);
            this.partitionMin = minResult != null ? minResult : Long.MIN_VALUE;
            this.partitionMax = maxResult != null ? maxResult : Long.MAX_VALUE;
        }
    }
}