Example usage for org.springframework.batch.item ExecutionContext put

List of usage examples for org.springframework.batch.item ExecutionContext put

Introduction

In this page you can find the example usage for org.springframework.batch.item ExecutionContext put.

Prototype

public void put(String key, @Nullable Object value) 

Source Link

Document

Add an Object value to the context.

Usage

From source file:org.emonocot.job.sitemap.StaxWriterTest.java

/**
 * @throws Exception//w  ww .  ja  va  2  s.co  m
 */
@Test
public void testWriteUrlToFile() throws Exception {
    String expectedXml = "<?xml version='1.0' encoding='UTF-8'?><urlset xmlns=\"http://www.sitemaps.org/schemas/sitemap\"><url><loc>http://build.e-monocot.org/test/identifier</loc><lastmod>1986-07-11T22:15:00.000+01:00</lastmod></url></urlset>";
    ExecutionContext executionContext = new ExecutionContext();
    executionContext.put("query.string", "from Taxon");
    writer.open(executionContext);
    ArrayList<Url> items = new ArrayList<Url>();
    Url data = new Url();
    data.setLastmod(ISODateTimeFormat.dateTime().print(new DateTime(1986, 07, 11, 22, 15, 00, 00)));
    data.setLoc(new URL("http://build.e-monocot.org/test/identifier"));
    items.add(data);
    writer.write(items);
    writer.close();
    assertTrue("The file should exist and be readable", tempFile.exists() && tempFile.isReadable());
    assertEquals("The XML produced didn't match expected XML", expectedXml,
            FileUtils.readFileToString(tempFile.getFile()));
}

From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testSimpleProperty() throws Exception {
    JobExecution jobExecution = new JobExecution(11L);
    ExecutionContext executionContext = jobExecution.getExecutionContext();
    executionContext.put("foo", "bar");
    JobSynchronizationManager.register(jobExecution);
    assertEquals("bar", simple.getName());
}

From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testGetMultipleInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        final Long id = 123L + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override/*from   ww  w  .j av  a2 s . c om*/
            public String call() throws Exception {
                JobExecution jobExecution = new JobExecution(id);
                ExecutionContext executionContext = jobExecution.getExecutionContext();
                executionContext.put("foo", value);
                JobContext context = JobSynchronizationManager.register(jobExecution);
                logger.debug("Registered: " + context.getJobExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    JobSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    int i = 0;
    for (FutureTask<String> task : tasks) {
        assertEquals("foo" + i, task.get());
        i++;
    }

}

From source file:org.springframework.batch.core.scope.AsyncJobScopeIntegrationTests.java

@Test
public void testGetSameInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();
    final JobExecution jobExecution = new JobExecution(11L);
    ExecutionContext executionContext = jobExecution.getExecutionContext();
    executionContext.put("foo", "foo");
    JobSynchronizationManager.register(jobExecution);
    assertEquals("foo", simple.getName());

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override/*from  w  ww  .  j a v  a 2s .c om*/
            public String call() throws Exception {
                ExecutionContext executionContext = jobExecution.getExecutionContext();
                executionContext.put("foo", value);
                JobContext context = JobSynchronizationManager.register(jobExecution);
                logger.debug("Registered: " + context.getJobExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    JobSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    for (FutureTask<String> task : tasks) {
        assertEquals("foo", task.get());
    }

    // Don't close the outer scope until all tasks are finished. This should
    // always be the case if using an AbstractJob
    JobSynchronizationManager.close();

}

From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java

@Test
public void testSimpleProperty() throws Exception {
    StepExecution stepExecution = new StepExecution("step", new JobExecution(0L), 123L);
    ExecutionContext executionContext = stepExecution.getExecutionContext();
    executionContext.put("foo", "bar");
    StepSynchronizationManager.register(stepExecution);
    assertEquals("bar", simple.getName());
}

From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java

@Test
public void testGetMultipleInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        final Long id = 123L + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override//from   w ww .j  a v a  2s  .c  o m
            public String call() throws Exception {
                StepExecution stepExecution = new StepExecution(value, new JobExecution(0L), id);
                ExecutionContext executionContext = stepExecution.getExecutionContext();
                executionContext.put("foo", value);
                StepContext context = StepSynchronizationManager.register(stepExecution);
                logger.debug("Registered: " + context.getStepExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    StepSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    int i = 0;
    for (FutureTask<String> task : tasks) {
        assertEquals("foo" + i, task.get());
        i++;
    }

}

From source file:org.springframework.batch.core.scope.AsyncStepScopeIntegrationTests.java

@Test
public void testGetSameInMultipleThreads() throws Exception {

    List<FutureTask<String>> tasks = new ArrayList<FutureTask<String>>();
    final StepExecution stepExecution = new StepExecution("foo", new JobExecution(0L), 123L);
    ExecutionContext executionContext = stepExecution.getExecutionContext();
    executionContext.put("foo", "foo");
    StepSynchronizationManager.register(stepExecution);
    assertEquals("foo", simple.getName());

    for (int i = 0; i < 12; i++) {
        final String value = "foo" + i;
        FutureTask<String> task = new FutureTask<String>(new Callable<String>() {
            @Override//from   ww  w  .ja v a 2 s .c  o m
            public String call() throws Exception {
                ExecutionContext executionContext = stepExecution.getExecutionContext();
                executionContext.put("foo", value);
                StepContext context = StepSynchronizationManager.register(stepExecution);
                logger.debug("Registered: " + context.getStepExecutionContext());
                try {
                    return simple.getName();
                } finally {
                    StepSynchronizationManager.close();
                }
            }
        });
        tasks.add(task);
        taskExecutor.execute(task);
    }

    for (FutureTask<String> task : tasks) {
        assertEquals("foo", task.get());
    }

    // Don't close the outer scope until all tasks are finished. This should
    // always be the case if using an AbstractStep
    StepSynchronizationManager.close();

}

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

/**
 * Partition a database table assuming that the data in the column specified
 * are uniformly distributed. The execution context values will have keys
 * <code>minValue</code> and <code>maxValue</code> specifying the range of
 * values to consider in each partition.
 *
 * @see Partitioner#partition(int)//from   ww  w .j av  a 2 s.  co  m
 */
@Override
public Map<String, ExecutionContext> partition(int gridSize) {
    StringBuilder incrementalClause = new StringBuilder();
    Map<String, ExecutionContext> result = new HashMap<>();

    if (!StringUtils.hasText(checkColumn) && !StringUtils.hasText(column)) {
        ExecutionContext value = new ExecutionContext();
        value.put("partClause", "");
        result.put("partition0", value);
        value.put("partSuffix", "");
    } else {
        if (StringUtils.hasText(checkColumn)) {
            incrementalClause.append(checkColumn).append(" > ").append(this.incrementalMin);
        }

        long targetSize = (this.partitionMax - this.partitionMin) / partitions + 1;

        int number = 0;
        long start = this.partitionMin;
        long end = start + targetSize - 1;

        while (start >= 0 && start <= this.partitionMax) {
            ExecutionContext value = new ExecutionContext();
            result.put("partition" + number, value);

            if (end >= this.partitionMax) {
                end = this.partitionMax;
            }

            if (StringUtils.hasText(checkColumn)) {
                value.putString("partClause", String.format("WHERE (%s BETWEEN %s AND %s) AND %s", column,
                        start, end, incrementalClause.toString()));
            } else {
                value.putString("partClause",
                        String.format("WHERE (%s BETWEEN %s AND %s)", column, start, end));
            }

            value.putString("partSuffix", "-p" + number);
            start += targetSize;
            end += targetSize;
            number++;

            log.debug("Current ExecutionContext = " + value);
        }
    }

    return result;
}

From source file:org.springframework.batch.item.database.JdbcPagingRestartIntegrationTests.java

@Test
@Ignore //FIXME/* w w  w  .j a v a 2 s.c  o m*/
public void testReaderOnRestart() throws Exception {

    ItemReader<Foo> reader = getItemReader();

    int total = JdbcTestUtils.countRowsInTable(jdbcTemplate, "T_FOOS");
    int count = (total / pageSize) * pageSize;
    int pagesToRead = Math.min(3, total / pageSize);
    if (count >= pagesToRead * pageSize) {
        count -= pagesToRead * pageSize;
    }

    ExecutionContext executionContext = new ExecutionContext();
    executionContext.putInt("JdbcPagingItemReader.read.count", count);
    // Assume the primary keys are in order

    List<Map<String, Object>> ids = jdbcTemplate.queryForList("SELECT ID,NAME FROM T_FOOS ORDER BY ID ASC");
    logger.debug("Ids: " + ids);
    int startAfterValue = (new Long(ids.get(count - 1).get("ID").toString())).intValue();
    logger.debug("Start after: " + startAfterValue);
    Map<String, Object> startAfterValues = new LinkedHashMap<String, Object>();
    startAfterValues.put("ID", startAfterValue);
    executionContext.put("JdbcPagingItemReader.start.after", startAfterValues);
    ((ItemStream) reader).open(executionContext);

    for (int i = count; i < total; i++) {
        Foo item = reader.read();
        logger.debug("Item: " + item);
        assertNotNull(item);
    }

    Foo item = reader.read();
    logger.debug("Item: " + item);
    assertNull(item);

}

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

/**
 * Get the restart data./* w  ww.jav a  2s  .  co m*/
 * 
 * @see org.springframework.batch.item.ItemStream#update(ExecutionContext)
 */
@Override
public void update(ExecutionContext executionContext) {
    super.update(executionContext);
    if (saveState) {
        Assert.notNull(executionContext, "ExecutionContext must not be null");
        executionContext.putLong(getExecutionContextKey(RESTART_DATA_NAME), getPosition());
        executionContext.putLong(getExecutionContextKey(WRITE_STATISTICS_NAME), currentRecordCount);
        if (!unclosedHeaderCallbackElements.isEmpty()) {
            executionContext.put(getExecutionContextKey(UNCLOSED_HEADER_CALLBACK_ELEMENTS_NAME),
                    unclosedHeaderCallbackElements);
        }
    }
}