Java 类org.springframework.batch.core.ExitStatus 实例源码

项目:powop    文件:SingleRecordQueryTasklet.java   
@Override
@Transactional
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    Query<String> query = currentSession().createQuery(queryString, String.class);
    query.setMaxResults(1);
    query.setFirstResult(0);

    try {
        String result = query.getSingleResult();
        chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("record.identifier", result);
        contribution.setExitStatus(new ExitStatus("MORE_RESULTS"));
    } catch (NoResultException e) {
        contribution.setExitStatus(new ExitStatus("NO_MORE_RESULTS"));
    }

    return RepeatStatus.FINISHED;
}
项目:batch-scheduler    文件:ProcTasklet.java   
@Override
public RepeatStatus execute(StepContribution stepContribution, ChunkContext chunkContext) {
    Object parametersObj = chunkContext.getStepContext().getJobParameters().get("JobParameters");
    String jobParameters = String.valueOf(System.currentTimeMillis());
    String params = "(";
    if (parametersObj != null) {
        jobParameters = parametersObj.toString();
        String[] p = jobParameters.split(" ");
        for (int i = 0; i < p.length; i++) {
            if (i == 0) {
                params += "'" + p[i] + "'";
            } else {
                params += ",'" + p[i] + "'";
            }
        }
    }
    params += ")";
    try {
        logger.info("program is :" + scriptFile + ", argument is:" + params);
        jdbcTemplate.execute("call " + scriptFile + params);
    } catch (Exception e) {
        logger.error(e.getMessage());
        chunkContext.getStepContext().getStepExecution().setExitStatus(ExitStatus.FAILED);
    }
    return RepeatStatus.FINISHED;
}
项目:oma-riista-web    文件:LHHuntingClubCSVCleaner.java   
@Override
public void afterJob(final JobExecution jobExecution) {
    if (ExitStatus.COMPLETED.equals(jobExecution.getExitStatus())) {
        final ExecutionContext executionContext = jobExecution.getExecutionContext();
        final String inputFile = executionContext.getString(LHHuntingClubBatchConfig.KEY_INPUT_FILE, null);

        if (inputFile != null) {
            final Path path = Paths.get(inputFile);

            try {
                LOG.info("Deleting temporary file: {}", inputFile);
                Files.deleteIfExists(path);

            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            LOG.warn("Input file not found in context");
        }
    }
}
项目:Spring-Batch-en-Castellano    文件:CustomConditionalTasklet.java   
@Override
public RepeatStatus execute(StepContribution arg0, ChunkContext arg1) throws Exception {

    Long time = Calendar.getInstance().getTimeInMillis();
    String exit;
    if(time % 2 == 0){
        exit = ExitStatus.NOOP.getExitCode().toString();
        arg0.setExitStatus(ExitStatus.NOOP);
    }else{
        exit = ExitStatus.COMPLETED.getExitCode().toString();
        arg0.setExitStatus(ExitStatus.COMPLETED);
    }

    System.out.println("Executing step with name " + taskletName + " and exitCode " + exit);

    return RepeatStatus.FINISHED;
}
项目:spring-cloud-dataflow    文件:DataflowTemplateTests.java   
private void assertCorrectMixins(RestTemplate restTemplate) {
    boolean containsMappingJackson2HttpMessageConverter = false;

    for (HttpMessageConverter<?> converter : restTemplate.getMessageConverters()) {
        if (converter instanceof MappingJackson2HttpMessageConverter) {
            containsMappingJackson2HttpMessageConverter = true;

            final MappingJackson2HttpMessageConverter jacksonConverter = (MappingJackson2HttpMessageConverter) converter;
            final ObjectMapper objectMapper = jacksonConverter.getObjectMapper();

            assertNotNull(objectMapper.findMixInClassFor(JobExecution.class));
            assertNotNull(objectMapper.findMixInClassFor(JobParameters.class));
            assertNotNull(objectMapper.findMixInClassFor(JobParameter.class));
            assertNotNull(objectMapper.findMixInClassFor(JobInstance.class));
            assertNotNull(objectMapper.findMixInClassFor(ExitStatus.class));
            assertNotNull(objectMapper.findMixInClassFor(StepExecution.class));
            assertNotNull(objectMapper.findMixInClassFor(ExecutionContext.class));
            assertNotNull(objectMapper.findMixInClassFor(StepExecutionHistory.class));
        }
    }

    if (!containsMappingJackson2HttpMessageConverter) {
        fail("Expected that the restTemplate's list of Message Converters contained a "
                + "MappingJackson2HttpMessageConverter");
    }
}
项目:eMonocot    文件:JobExecutionDaoImpl.java   
/**
 * @param resultSet Set the result set
 * @param rowNumber Set the row number
 * @throws SQLException if there is a problem
 * @return a job execution instance
 */
public final JobExecution mapRow(final ResultSet resultSet,
        final int rowNumber) throws SQLException {
    JobInstance jobInstance = new JobInstance(resultSet.getBigDecimal(
            "JOB_INSTANCE_ID").longValue(),
            new JobParameters(), resultSet.getString("JOB_NAME"));
    JobExecution jobExecution = new JobExecution(jobInstance,
            resultSet.getBigDecimal("JOB_EXECUTION_ID").longValue());
    jobExecution.setStartTime(resultSet.getTimestamp("START_TIME"));
    jobExecution.setCreateTime(resultSet.getTimestamp("CREATE_TIME"));
    jobExecution.setEndTime(resultSet.getTimestamp("END_TIME"));
    jobExecution.setStatus(BatchStatus.valueOf(resultSet
            .getString("STATUS")));
    ExitStatus exitStatus = new ExitStatus(
            resultSet.getString("EXIT_CODE"),
            resultSet.getString("EXIT_MESSAGE"));
    jobExecution.setExitStatus(exitStatus);
    return jobExecution;
}
项目:eMonocot    文件:CheckEmptyResponseTasklet.java   
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    BufferedInputStream bufferedInputStream = new BufferedInputStream(inputFile.getInputStream());
    char[] buffer = new char[2];
    InputStreamReader inputStreamReader = new InputStreamReader(bufferedInputStream);
    int numChars = -1;
    if((numChars = inputStreamReader.read(buffer)) == 2) {
        String string = new String(buffer);
        if(string.equals("[]")) {
            contribution.setExitStatus(new ExitStatus("EMPTY_RESPONSE").addExitDescription("The webservice returned an empty list of taxa"));
        }
    } else {
        contribution.setExitStatus(ExitStatus.FAILED.addExitDescription("Unable to read the webservice response"));
    }

    inputStreamReader.close();

    return RepeatStatus.FINISHED;
}
项目:eMonocot    文件:SitemapFilesListener.java   
public ExitStatus afterStep(StepExecution stepExecution) {
    logger.debug("After Step " + currentStep.getStepName());

    try {
        Url u = new Url();
        u.setLastmod(ISODateTimeFormat.dateTime().print((ReadableInstant) null));
        u.setLoc(new URL(portalBaseUrl +"/" + sitemapDir + "/" + currentFile.getFilename()));
        sitemapNames.add(u);
    } catch (MalformedURLException e) {
        logger.error("Unable create Url for sitemap", e);
    }

    //reset counts to nulls to support beforeStep()
    currentStep = null;
    currentFile = null;
    chunkOfFile = 0;
    commitSize = 0;

    return stepExecution.getExitStatus();
}
项目:eMonocot    文件:FileResourceZipper.java   
/**
 * @param source The directory containing the DwC/A files
 * @param target The absolute filepath for where to write the archive
 * @return
 */
public static final ExitStatus packArchive(final String source, final String target) {

    logger.info("Attempting to pack " + source + " to " +  target);
    try { //to wrap things we can de-reference immediately
        File sourceDir = new File(source);
        if(!sourceDir.exists()) {
            throw new FileNotFoundException("Unable to find filesystem resource - " + source);
        }
        if(!sourceDir.isDirectory()) {
            throw new IllegalArgumentException(source + " is not a folder");
        }

        zip(source, target);
        return ExitStatus.COMPLETED;
    } catch (Exception e) {
        logger.error("Error writing " + source + " to " + target, e);
        return ExitStatus.FAILED;
    }
}
项目:eMonocot    文件:SingleRecordQueryTasklet.java   
@Override
@Transactional
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    Query query = this.getSession().createQuery(queryString);
    query.setMaxResults(1);
    query.setFirstResult(0);

    List<String> results = (List<String>)query.list();

    if(results.size() == 0) {
        contribution.setExitStatus(new ExitStatus("NO_MORE_RESULTS"));
    } else {
        chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("record.identifier", results.get(0));
        contribution.setExitStatus(new ExitStatus("MORE_RESULTS"));
    }


    return RepeatStatus.FINISHED;
}
项目:eMonocot    文件:FlatFileCreatorIntegrationTest.java   
/**
 * @throws Exception
 */
@Test
public void testWriteTaxonFile() throws Exception {
    Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
    parameters.put("query", new JobParameter(""));
    parameters.put("selected.facets", new JobParameter("taxon.family_ss=Araceae"));
    parameters.put("download.taxon", new JobParameter(toParameter(DarwinCorePropertyMap.getConceptTerms(DwcTerm.Taxon))));
    parameters.put("download.file", new JobParameter(UUID.randomUUID().toString() + ".txt"));
    parameters.put("download.limit", new JobParameter(new Integer(Integer.MAX_VALUE).toString()));
    parameters.put("download.fieldsTerminatedBy", new JobParameter("\t"));
    parameters.put("download.fieldsEnclosedBy", new JobParameter("\""));
    parameters.put("download.format", new JobParameter("taxon"));

    JobParameters jobParameters = new JobParameters(parameters);
    Job archiveCreatorJob = jobLocator.getJob("FlatFileCreation");
    assertNotNull("flatFileCreatorJob must exist", archiveCreatorJob);
    JobExecution jobExecution = jobLauncher.run(archiveCreatorJob,
            jobParameters);

    assertEquals("The Job should be sucessful", ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
项目:eMonocot    文件:FlatFileCreatorIntegrationTest.java   
@Test
public void testWriteChecklistPdf() throws Exception {
    Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
    parameters.put("query", new JobParameter(""));
    parameters.put("selected.facets", new JobParameter("taxon.family_ss=Araceae"));
    parameters.put("download.taxon", new JobParameter(toParameter(DarwinCorePropertyMap.getConceptTerms(DwcTerm.Taxon))));
    parameters.put("download.file", new JobParameter(UUID.randomUUID().toString() + ".pdf"));
    parameters.put("download.limit", new JobParameter(new Integer(Integer.MAX_VALUE).toString()));
    parameters.put("download.fieldsTerminatedBy", new JobParameter("\t"));
    parameters.put("download.fieldsEnclosedBy", new JobParameter("\""));
    parameters.put("download.sort", new JobParameter("searchable.label_sort_asc"));
    parameters.put("download.format", new JobParameter("hierarchicalChecklist"));
    parameters.put("download.template.filepath", new JobParameter("org/emonocot/job/download/reports/name_report1.jrxml"));

    JobParameters jobParameters = new JobParameters(parameters);
    Job archiveCreatorJob = jobLocator.getJob("FlatFileCreation");
    assertNotNull("flatFileCreator Job must exist", archiveCreatorJob);
    JobExecution jobExecution = jobLauncher.run(archiveCreatorJob,
            jobParameters);

    assertEquals("The Job should be sucessful", ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
项目:eMonocot    文件:GetResourceClientTest.java   
/**
 *
 * @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 * @throws SAXException
 *             if the content retrieved is not valid xml.
 */
@Test
public final void testGetResourceSuccessfully() throws IOException,
SAXException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();

    EasyMock.expect(httpClient.getParams())
    .andReturn(new BasicHttpParams());
    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class)))
    .andReturn(httpResponse);
    EasyMock.replay(httpClient);

    ExitStatus exitStatus = getResourceClient
            .getResource(testzip,
                    Long.toString(new Date().getTime()),
                    tempFile.getAbsolutePath());

    EasyMock.verify(httpClient);

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be COMPLETED", exitStatus,
            ExitStatus.COMPLETED);
}
项目:eMonocot    文件:GetResourceClientTest.java   
/**
 *
 * @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
public final void testGetResourceNotModified() throws IOException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    httpResponse.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_0,
            HttpStatus.SC_NOT_MODIFIED, "Not Modified"));

    EasyMock.expect(httpClient.getParams())
    .andReturn(new BasicHttpParams());
    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class)))
    .andReturn(httpResponse);
    EasyMock.replay(httpClient);

    ExitStatus exitStatus = getResourceClient
            .getResource(testzip,
                    Long.toString(new Date().getTime()),
                    tempFile.getAbsolutePath());

    EasyMock.verify(httpClient);

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be NOT_MODIFIED",
            exitStatus.getExitCode(), "NOT_MODIFIED");
}
项目:eMonocot    文件:GetResourceClientTest.java   
/**
 *
    @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
public final void testGetDocumentAnyOtherStatus() throws IOException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    httpResponse.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_0,
            HttpStatus.SC_BAD_REQUEST, "Bad Request"));

    EasyMock.expect(httpClient.getParams())
    .andReturn(new BasicHttpParams());
    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class)))
    .andReturn(httpResponse).anyTimes();
    EasyMock.replay(httpClient);

    ExitStatus exitStatus = getResourceClient
            .getResource(testzip,
                    Long.toString(new Date().getTime()),
                    tempFile.getAbsolutePath());

    EasyMock.verify(httpClient);

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be FAILED", exitStatus,
            ExitStatus.FAILED);
}
项目:eMonocot    文件:GetResourceClientIntegrationTest.java   
/**
 *
 * @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 * @throws SAXException
 *             if the content retrieved is not valid xml.
 */
@Test
public final void testGetResourceSuccessfully() throws IOException,
SAXException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();

    String repository = properties.getProperty("test.resource.baseUrl");

    ExitStatus exitStatus = getResourceClient
            .getResource(repository + "dwc.zip",
                    Long.toString(PAST_DATETIME.getMillis()),
                    tempFile.getAbsolutePath());

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be COMPLETED", ExitStatus.COMPLETED, exitStatus);
}
项目:eMonocot    文件:GetResourceClientIntegrationTest.java   
/**
 * This works on a normal apache httpd directory, but not for GIT
 * @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
@Ignore
public final void testGetResourceNotModified() throws IOException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    String repository = properties.getProperty("test.resource.baseUrl");

    ExitStatus exitStatus = getResourceClient
            .getResource(repository + "dwc.zip",
                    Long.toString(new Date().getTime() - 60000L),
                    tempFile.getAbsolutePath());

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be NOT_MODIFIED", "NOT_MODIFIED", exitStatus.getExitCode());
}
项目:eMonocot    文件:GetResourceClientIntegrationTest.java   
/**
 *
    @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
public final void testGetDocumentAnyOtherStatus() throws IOException {
    AttemptCountingRetryListener retryListener = new AttemptCountingRetryListener();
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    getResourceClient.setRetryListeners(new RetryListener[] {
            retryListener
    });

    ExitStatus exitStatus = getResourceClient
            .getResource("http://not.a.domain.invalid/test.zip",
                    Long.toString(new Date().getTime()),
                    tempFile.getAbsolutePath());

    assertNotNull("ExitStatus should not be null.", exitStatus);
    assertEquals("ExitStatus should be FAILED.", ExitStatus.FAILED, exitStatus);
    assertEquals("There should be three retry attempts.", 3, retryListener.getErrors());
}
项目:marklogic-spring-batch    文件:StepExecutionAdapter.java   
@Override
public StepExecution unmarshal(AdaptedStepExecution v) throws Exception {
    JobExecution je = new JobExecution(v.getJobExecutionId());
    JobInstance ji = new JobInstance(v.getJobInstanceId(), v.getJobName());
    je.setJobInstance(ji);
    StepExecution step = new StepExecution(v.getStepName(), je);
    step.setId(v.getId());
    step.setStartTime(v.getStartTime());
    step.setEndTime(v.getEndTime());
    step.setReadSkipCount(v.getReadSkipCount());
    step.setWriteSkipCount(v.getWriteSkipCount());
    step.setProcessSkipCount(v.getProcessSkipCount());
    step.setReadCount(v.getReadCount());
    step.setWriteCount(v.getWriteCount());
    step.setFilterCount(v.getFilterCount());
    step.setRollbackCount(v.getRollbackCount());
    step.setExitStatus(new ExitStatus(v.getExitCode()));
    step.setLastUpdated(v.getLastUpdated());
    step.setVersion(v.getVersion());
    step.setStatus(v.getStatus());
    step.setExecutionContext(v.getExecutionContext());
    return step;
}
项目:powop    文件:CheckingStepExcutionListener.java   
@Override
public ExitStatus afterStep(StepExecution step) {
    List<Throwable> exceptions = step.getFailureExceptions();

    if(exceptions != null && !exceptions.isEmpty()){
        ExitStatus exitStatus = new ExitStatus("DELETE FAILED");
        for(Throwable exception : exceptions){
            if(ResourceIsNotDeletableException.class.isInstance(exception.getCause())){
                String message = exception.getMessage();
                if(message != null){
                    exitStatus.addExitDescription(message);
                    logger.debug(exitStatus.toString());
                    return exitStatus;
                }

            }else{
                exitStatus.addExitDescription("unknown failure - this resource could not be deleted");
                logger.debug(exitStatus.toString());
                return exitStatus;
            }
        }
    }
    logger.debug("READY FOR DELETE");
    return new ExitStatus("READY FOR DELETE");
}
项目:powop    文件:FileResourceZipper.java   
/**
 * @param source The directory containing the DwC/A files
 * @param target The absolute filepath for where to write the archive
 * @return
 */
public static final ExitStatus packArchive(final String source, final String target) {

    logger.info("Attempting to pack " + source + " to " +  target);
    try { //to wrap things we can de-reference immediately
        File sourceDir = new File(source);
        if(!sourceDir.exists()) {
            throw new FileNotFoundException("Unable to find filesystem resource - " + source);
        }
        if(!sourceDir.isDirectory()) {
            throw new IllegalArgumentException(source + " is not a folder");
        }

        zip(source, target);
        return ExitStatus.COMPLETED;
    } catch (Exception e) {
        logger.error("Error writing " + source + " to " + target, e);
        return ExitStatus.FAILED;
    }
}
项目:powop    文件:GetResourceClient.java   
public ExitStatus getWithRetry(RetryCallback<ExitStatus, Exception> callback) {
    RetryTemplate retryTemplate = new RetryTemplate();
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    Map<Class<? extends Throwable>,Boolean> retryableExceptions = new HashMap<Class<? extends Throwable>,Boolean>();
    retryableExceptions.put(ClientProtocolException.class, Boolean.TRUE);
    retryableExceptions.put(IOException.class, Boolean.TRUE);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(retryAttempts, retryableExceptions);
    backOffPolicy.setBackOffPeriod(backoffPeriod);

    retryTemplate.setListeners(retryListeners);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    retryTemplate.setRetryPolicy(retryPolicy);

    try {
        return retryTemplate.execute(callback);
    } catch (Exception e) {
        logger.error("Retry processing failed " + e.getMessage());
        return ExitStatus.FAILED;
    }
}
项目:powop    文件:FlatFileCreatorIntegrationTest.java   
/**
 * @throws Exception
 */
@Test
public void testWriteTaxonFile() throws Exception {
    Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
    parameters.put("query", new JobParameter(""));
    parameters.put("selected.facets", new JobParameter("taxon.family_ss=Araceae"));
    parameters.put("download.taxon", new JobParameter(toParameter(DarwinCorePropertyMap.getConceptTerms(DwcTerm.Taxon))));
    parameters.put("download.file", new JobParameter(UUID.randomUUID().toString() + ".txt"));
    parameters.put("download.limit", new JobParameter(new Integer(Integer.MAX_VALUE).toString()));
    parameters.put("download.fieldsTerminatedBy", new JobParameter("\t"));
    parameters.put("download.fieldsEnclosedBy", new JobParameter("\""));
    parameters.put("download.format", new JobParameter("taxon"));

    JobParameters jobParameters = new JobParameters(parameters);
    Job archiveCreatorJob = jobLocator.getJob("FlatFileCreation");
    assertNotNull("flatFileCreatorJob must exist", archiveCreatorJob);
    JobExecution jobExecution = jobLauncher.run(archiveCreatorJob,
            jobParameters);


    assertEquals("The Job should be sucessful", ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
项目:powop    文件:FlatFileCreatorIntegrationTest.java   
@Test
public void testWriteChecklistPdf() throws Exception {
    Map<String, JobParameter> parameters = new HashMap<String, JobParameter>();
    parameters.put("query", new JobParameter(""));
    parameters.put("selected.facets", new JobParameter("taxon.family_ss=Araceae"));
    parameters.put("download.taxon", new JobParameter(toParameter(DarwinCorePropertyMap.getConceptTerms(DwcTerm.Taxon))));
    parameters.put("download.file", new JobParameter(UUID.randomUUID().toString() + ".pdf"));
    parameters.put("download.limit", new JobParameter(new Integer(Integer.MAX_VALUE).toString()));
    parameters.put("download.fieldsTerminatedBy", new JobParameter("\t"));
    parameters.put("download.fieldsEnclosedBy", new JobParameter("\""));
    parameters.put("download.sort", new JobParameter("searchable.label_sort_asc"));
    parameters.put("download.format", new JobParameter("hierarchicalChecklist"));
    parameters.put("download.template.filepath", new JobParameter("org/emonocot/job/download/reports/name_report1.jrxml"));

    JobParameters jobParameters = new JobParameters(parameters);
    Job archiveCreatorJob = jobLocator.getJob("FlatFileCreation");
    assertNotNull("flatFileCreator Job must exist", archiveCreatorJob);
    JobExecution jobExecution = jobLauncher.run(archiveCreatorJob,
            jobParameters);

    assertEquals("The Job should be sucessful", ExitStatus.COMPLETED, jobExecution.getExitStatus());
}
项目:powop    文件:GetResourceClientTest.java   
/**
 *
 * @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 * @throws SAXException
 *             if the content retrieved is not valid xml.
 */
@Test
public final void testGetResourceSuccessfully() throws IOException,
SAXException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();

    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class)))
    .andReturn(httpResponse);
    EasyMock.replay(httpClient);

    ExitStatus exitStatus = getResourceClient
            .getResource(testzip,
                    tempFile.getAbsolutePath(),
                    Long.toString(new Date().getTime()));

    EasyMock.verify(httpClient);

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be COMPLETED", exitStatus,
            ExitStatus.COMPLETED);
}
项目:powop    文件:GetResourceClientTest.java   
/**
 *
 * @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
public final void testGetResourceNotModified() throws IOException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    httpResponse.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_0,
            HttpStatus.SC_NOT_MODIFIED, "Not Modified"));

    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class)))
    .andReturn(httpResponse);
    EasyMock.replay(httpClient);

    ExitStatus exitStatus = getResourceClient
            .getResource(testzip,
                    tempFile.getAbsolutePath(),
                    Long.toString(new Date().getTime()));

    EasyMock.verify(httpClient);

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be NOT_MODIFIED",
            exitStatus.getExitCode(), "NOT_MODIFIED");
}
项目:powop    文件:GetResourceClientTest.java   
/**
 *
    @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
public final void testGetDocumentAnyOtherStatus() throws IOException {
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    httpResponse.setStatusLine(new BasicStatusLine(HttpVersion.HTTP_1_0,
            HttpStatus.SC_BAD_REQUEST, "Bad Request"));

    EasyMock.expect(httpClient.execute(EasyMock.isA(HttpGet.class)))
    .andReturn(httpResponse).anyTimes();
    EasyMock.replay(httpClient);

    ExitStatus exitStatus = getResourceClient
            .getResource(testzip,
                    tempFile.getAbsolutePath(),
                    Long.toString(new Date().getTime()));

    EasyMock.verify(httpClient);

    assertNotNull("ExitStatus should not be null", exitStatus);
    assertEquals("ExitStatus should be FAILED", exitStatus,
            ExitStatus.FAILED);
}
项目:powop    文件:GetResourceClientIntegrationTest.java   
/**
 *
    @throws IOException
 *             if a temporary file cannot be created or if there is a http
 *             protocol error.
 */
@Test
@Ignore
public final void testGetDocumentAnyOtherStatus() throws IOException {
    AttemptCountingRetryListener retryListener = new AttemptCountingRetryListener();
    File tempFile = File.createTempFile("test", "zip");
    tempFile.deleteOnExit();
    getResourceClient.setRetryListeners(new RetryListener[] { retryListener });

    ExitStatus exitStatus = getResourceClient.getResource("http://not.a.domain.invalid/test.zip",
                    tempFile.getAbsolutePath(),
                    Long.toString(new Date().getTime()));

    assertNotNull("ExitStatus should not be null.", exitStatus);
    assertEquals("ExitStatus should be FAILED.", ExitStatus.FAILED, exitStatus);
    assertEquals("There should be three retry attempts.", 3, retryListener.getErrors());
}
项目:olat    文件:CampusInterceptor.java   
/**
 * Generates an appropriate statistic of the processed, <br>
 * delegates the cleanup and the metric notification.
 * 
 * @param se
 *            the StepExecution
 */
@Override
@Transactional(propagation = Propagation.REQUIRES_NEW)
public ExitStatus afterStep(StepExecution se) {
    LOG.info(se);

    statisticDao.save(createImportStatistic(se));

    if (CampusProcessStep.IMPORT_CONTROLFILE.name().equalsIgnoreCase(se.getStepName())) {
        if (se.getWriteCount() != getFixedNumberOfFilesToBeExported()) {
            // if (se.getReadCount() != getFixedNumberOfFilesToBeExported() || se.getWriteCount() != getFixedNumberOfFilesToBeExported()) {
            notifyMetrics(se);
            return ExitStatus.FAILED;
        }
    }

    removeOldDataIfExist(se);
    notifyMetrics(se);

    return null;
}
项目:spring-xd-jdbc-job    文件:JdbcTasklet.java   
/**
 * Execute the {@link #setSql(String) SQL query} provided. If the query starts with "select" (case insensitive) the
 * result is a list of maps, which is logged and added to the step execution exit status. Otherwise the query is
 * executed and the result is an indication, also in the exit status, of the number of rows updated.
 */
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    StepExecution stepExecution = chunkContext.getStepContext().getStepExecution();
    ExitStatus exitStatus = stepExecution.getExitStatus();

    String msg = "";
    if (StringUtils.hasText(sql)) {
        msg = runCommand(chunkContext.getStepContext(), sql);
    } else if (!CollectionUtils.isEmpty(scripts)) {
        msg = runScripts(chunkContext, scripts, null);
    }

    stepExecution.setExitStatus(exitStatus.addExitDescription(msg));
    return RepeatStatus.FINISHED;
}
项目:batchers    文件:TaxCalculationStepITest.java   
@Test
public void taxCalculationStep_generatesCorrectCalculation() throws Exception {
    Employee employee = haveOneEmployee();

    JobParameters jobParameters = new JobParametersBuilder()
            .addLong("year", 2014L, true)
            .addLong("month", 5L, true)
            .toJobParameters();

    JobExecution jobExecution = jobLauncherTestUtils.launchStep(EmployeeJobConfigSingleJvm.TAX_CALCULATION_STEP, jobParameters);

    assertThat(jobExecution.getExitStatus()).isEqualTo(ExitStatus.COMPLETED);

    List<TaxCalculation> byEmployee = taxCalculationRepository.findByEmployee(employee);

    assertThat(byEmployee).hasSize(1);
    TaxCalculation taxCalculation = byEmployee.get(0);
    assertThat(taxCalculation.getEmployee().getId()).isEqualTo(employee.getId());
    assertThat(taxCalculation.getYear()).isEqualTo(2014);
    assertThat(taxCalculation.getMonth()).isEqualTo(5);

    List<TaxCalculation> byYearAndMonth = taxCalculationRepository.find(2014, 5, 1L);
    assertThat(byYearAndMonth).hasSize(1);
}
项目:spring-boot-starter-batch-web    文件:MetricsListener.java   
@Override
public ExitStatus afterStep(StepExecution stepExecution) {
    // Calculate step execution time
    // Why is stepExecution.getEndTime().getTime() not available here? (see AbstractStep)
    long stepDuration = System.currentTimeMillis() - stepExecution.getStartTime().getTime();
    gaugeService.submit(TIMER_PREFIX + getStepExecutionIdentifier(stepExecution) + ".duration", stepDuration);
    long itemCount = stepExecution.getWriteCount() + stepExecution.getSkipCount();
    gaugeService.submit(GAUGE_PREFIX + getStepExecutionIdentifier(stepExecution) + ".item.count", itemCount);
    // Calculate execution time per item
    long durationPerItem = 0;
    if (itemCount > 0) {
        durationPerItem = stepDuration / itemCount;
    }
    gaugeService.submit(TIMER_PREFIX + getStepExecutionIdentifier(stepExecution) + ".item.duration", durationPerItem);
    // Export metrics from StepExecution to MetricRepositories
    Set<Entry<String, Object>> metrics = stepExecution.getExecutionContext().entrySet();
    for (Entry<String, Object> metric : metrics) {
        if (metric.getValue() instanceof Long) {
            gaugeService.submit(GAUGE_PREFIX + getStepExecutionIdentifier(stepExecution) + "." + metric.getKey(), (Long) metric.getValue());
        } else if (metric.getValue() instanceof Double) {
            gaugeService.submit(GAUGE_PREFIX + getStepExecutionIdentifier(stepExecution) + "." + metric.getKey(), (Double) metric.getValue());
        }
    }
    return null;
}
项目:spring-boot-starter-batch-web    文件:ProtocolListenerTest.java   
@Test
public void createProtocol() throws Exception {
    // Given
    JobExecution jobExecution = new JobExecution(1L, new JobParametersBuilder().addString("test", "value").toJobParameters());
    jobExecution.setJobInstance(new JobInstance(1L, "test-job"));
    jobExecution.setCreateTime(new Date());
    jobExecution.setStartTime(new Date());
    jobExecution.setEndTime(new Date());
    jobExecution.setExitStatus(new ExitStatus("COMPLETED_WITH_ERRORS", "This is a default exit message"));
    jobExecution.getExecutionContext().put("jobCounter", 1);
    StepExecution stepExecution = jobExecution.createStepExecution("test-step-1");
    stepExecution.getExecutionContext().put("stepCounter", 1);
    ProtocolListener protocolListener = new ProtocolListener();
    // When
    protocolListener.afterJob(jobExecution);
    // Then
    String output = this.outputCapture.toString();
    assertThat(output, containsString("Protocol for test-job"));
    assertThat(output, containsString("COMPLETED_WITH_ERRORS"));
}
项目:spring-ldap    文件:MappingLdifReaderTest.java   
@Test
public void testValidRun() {
    try {
        JobExecution jobExecution = this.launchStep("step1");

        //Ensure job completed successfully.
        Assert.isTrue(jobExecution.getExitStatus().equals(ExitStatus.COMPLETED), "Step Execution did not complete normally: " + jobExecution.getExitStatus());

        //Check output.
        Assert.isTrue(actual.exists(), "Actual does not exist.");
        AssertFile.assertFileEquals(expected.getFile(), actual.getFile());

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
项目:spring-ldap    文件:LdifReaderTest.java   
@Test
public void testValidRun() {
    try {
        JobExecution jobExecution = this.launchStep("step1");

        //Ensure job completed successfully.
        Assert.isTrue(jobExecution.getExitStatus().equals(ExitStatus.COMPLETED), "Step Execution did not complete normally: " + jobExecution.getExitStatus());

        //Check output.
        Assert.isTrue(actual.exists(), "Actual does not exist.");
        AssertFile.assertFileEquals(expected.getFile(), actual.getFile());

    } catch (Exception e) {
        e.printStackTrace();
        fail(e.getMessage());
    }
}
项目:musicbrainz-elasticsearch    文件:IndexBatchMain.java   
public static void main(String... args) {
    AbstractApplicationContext context = null;
    try {
        context = new ClassPathXmlApplicationContext(new String[] {
                "com/javaetmoi/elasticsearch/musicbrainz/batch/applicationContext-datasource.xml",
                "com/javaetmoi/elasticsearch/musicbrainz/batch/applicationContext-elasticsearch.xml",
                "com/javaetmoi/elasticsearch/musicbrainz/batch/applicationContext-batch.xml" });

        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job musicAlbumJob = context.getBean("musicAlbumJob", Job.class);
        jobLauncher.run(musicAlbumJob, new JobParameters());
    } catch (Throwable e) {
        String message = "Job Terminated in error: " + e.getMessage();
        LOG.error(message, e);
        systemExiter.exit(exitCodeMapper.intValue(ExitStatus.FAILED.getExitCode()));
    } finally {
        if (context != null) {
            context.close();
        }
    }
    systemExiter.exit(exitCodeMapper.intValue(ExitStatus.COMPLETED.getExitCode()));
}
项目:composed-task-runner    文件:ComposedTaskStepExecutionListenerTests.java   
@Test
public void testSuccessfulRun() {
    TaskExecution taskExecution = getDefaultTaskExecution(0, null);
    when(this.taskExplorer.getTaskExecution(anyLong())).thenReturn(taskExecution);
    populateExecutionContext(111L);
    assertEquals(ExitStatus.COMPLETED, this.taskListener.afterStep(this.stepExecution));
}
项目:composed-task-runner    文件:ComposedTaskStepExecutionListenerTests.java   
@Test
public void testExitMessageRunSuccess() {
    ExitStatus expectedTaskStatus = new ExitStatus("TEST_EXIT_MESSAGE");
    TaskExecution taskExecution = getDefaultTaskExecution(0,
            expectedTaskStatus.getExitCode());
    when(this.taskExplorer.getTaskExecution(anyLong())).thenReturn(taskExecution);
    populateExecutionContext(111L);

    assertEquals(expectedTaskStatus, this.taskListener.afterStep(this.stepExecution));
}
项目:composed-task-runner    文件:ComposedTaskStepExecutionListenerTests.java   
@Test
public void testExitMessageRunFail() {
    ExitStatus expectedTaskStatus = new ExitStatus("TEST_EXIT_MESSAGE");
    TaskExecution taskExecution = getDefaultTaskExecution(1,
            expectedTaskStatus.getExitCode());
    when(this.taskExplorer.getTaskExecution(anyLong())).thenReturn(taskExecution);
    populateExecutionContext(111L);

    assertEquals(expectedTaskStatus, this.taskListener.afterStep(this.stepExecution));
}
项目:composed-task-runner    文件:ComposedTaskStepExecutionListenerTests.java   
@Test
public void testFailedRun() {
    TaskExecution taskExecution = getDefaultTaskExecution(1, null);
    when(this.taskExplorer.getTaskExecution(anyLong())).thenReturn(taskExecution);
    populateExecutionContext(111L);

    assertEquals(ExitStatus.FAILED, this.taskListener.afterStep(this.stepExecution));
}