@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; }
@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; }
@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"); } } }
@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; }
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"); } }
/** * @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; }
@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; }
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(); }
/** * @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; } }
@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; }
/** * @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()); }
@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()); }
/** * * @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); }
/** * * @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"); }
/** * @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); }
/** * * @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); }
/** * 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()); }
/** * @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()); }
@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; }
@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"); }
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; } }
/** * * @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); }
/** * * @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"); }
/** * @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); }
/** * @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()); }
/** * 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; }
/** * 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; }
@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); }
@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; }
@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")); }
@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()); } }
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())); }
@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)); }
@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)); }
@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)); }
@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)); }