Example usage for org.springframework.batch.repeat RepeatStatus CONTINUABLE

List of usage examples for org.springframework.batch.repeat RepeatStatus CONTINUABLE

Introduction

In this page you can find the example usage for org.springframework.batch.repeat RepeatStatus CONTINUABLE.

Prototype

RepeatStatus CONTINUABLE

To view the source code for org.springframework.batch.repeat RepeatStatus CONTINUABLE.

Click Source Link

Document

Indicates that processing can continue.

Usage

From source file:info.smartkit.hairy_batman.jobs.TaskParseWxArticle.java

/**
 * {@inheritDoc}//from  w w  w.j  a  va2  s  .  c  o m
 */
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
    LOG.info("execute");
    return RepeatStatus.CONTINUABLE;
}

From source file:com.sinet.gage.tasklets.DominFullImportTasklet.java

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    if (!loginToDlapServer)
        loginToDlap();/* ww w. jav a2s . c om*/

    if (stateDomains == null)
        stateDomains = dlapDomainClient.getDomainReponseList(null, parentDomainId, "", "", 10000);

    if (stateCounter < stateDomains.size()) {
        DomainResponse stateDomain = stateDomains.get(stateCounter);
        currentStateName = stateDomain.getName();
        logger.info("DomainFullImportTasklet importing domain of state ### " + currentStateName);
        List<Domain> childDomains = getAllChildDomains(stateDomain);

        insertDomainsForState(childDomains, currentStateName);

        stateCounter++;
        return RepeatStatus.CONTINUABLE;
    } else {
        logger.info("DomainFullImportTasklet executed ...");

        return RepeatStatus.FINISHED;
    }
}

From source file:org.springframework.batch.core.jsr.step.item.JsrChunkProcessor.java

/**
 * Loops through reading (via {@link #provide(StepContribution, Chunk)} and
 * processing (via {@link #transform(StepContribution, Object)}) until the chunk
 * is complete.  Once the chunk is complete, the results are written (via
 * {@link #persist(StepContribution, Chunk)}.
 *
 * @see ChunkProcessor#process(StepContribution, Chunk)
 * @param contribution a {@link StepContribution}
 * @param chunk a {@link Chunk}//from ww w  .  j  a  v a 2  s  . co  m
 */
@Override
public void process(final StepContribution contribution, final Chunk<I> chunk) throws Exception {

    final AtomicInteger filterCount = new AtomicInteger(0);
    final Chunk<O> output = new Chunk<O>();

    repeatTemplate.iterate(new RepeatCallback() {

        @Override
        public RepeatStatus doInIteration(RepeatContext context) throws Exception {
            I item = provide(contribution, chunk);

            if (item != null) {
                contribution.incrementReadCount();
            } else {
                return RepeatStatus.FINISHED;
            }

            O processedItem = transform(contribution, item);

            if (processedItem == null) {
                filterCount.incrementAndGet();
            } else {
                output.add(processedItem);
            }

            return RepeatStatus.CONTINUABLE;
        }
    });

    contribution.incrementFilterCount(filterCount.get());
    if (output.size() > 0) {
        persist(contribution, output);
    }
}

From source file:org.springframework.batch.core.step.item.ChunkOrientedTasklet.java

@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {

    @SuppressWarnings("unchecked")
    Chunk<I> inputs = (Chunk<I>) chunkContext.getAttribute(INPUTS_KEY);
    if (inputs == null) {
        inputs = chunkProvider.provide(contribution);
        if (buffering) {
            chunkContext.setAttribute(INPUTS_KEY, inputs);
        }//from ww  w.j a  va 2  s  .  c o  m
    }

    chunkProcessor.process(contribution, inputs);
    chunkProvider.postProcess(contribution, inputs);

    // Allow a message coming back from the processor to say that we
    // are not done yet
    if (inputs.isBusy()) {
        logger.debug("Inputs still busy");
        return RepeatStatus.CONTINUABLE;
    }

    chunkContext.removeAttribute(INPUTS_KEY);
    chunkContext.setComplete();

    if (logger.isDebugEnabled()) {
        logger.debug("Inputs not busy, ended: " + inputs.isEnd());
    }
    return RepeatStatus.continueIf(!inputs.isEnd());

}

From source file:org.springframework.batch.core.step.item.SimpleChunkProvider.java

@Override
public Chunk<I> provide(final StepContribution contribution) throws Exception {

    final Chunk<I> inputs = new Chunk<I>();
    repeatOperations.iterate(new RepeatCallback() {

        @Override//from  ww  w .  jav  a 2 s  . co m
        public RepeatStatus doInIteration(final RepeatContext context) throws Exception {
            I item = null;
            try {
                item = read(contribution, inputs);
            } catch (SkipOverflowException e) {
                // read() tells us about an excess of skips by throwing an
                // exception
                return RepeatStatus.FINISHED;
            }
            if (item == null) {
                inputs.setEnd();
                return RepeatStatus.FINISHED;
            }
            inputs.add(item);
            contribution.incrementReadCount();
            return RepeatStatus.CONTINUABLE;
        }

    });

    return inputs;

}

From source file:org.springframework.batch.repeat.support.RepeatTemplate.java

/**
 * Execute the batch callback until the completion policy decides that we
 * are finished. Wait for the whole batch to finish before returning even if
 * the task executor is asynchronous./*from w w  w  .  java 2  s  . co  m*/
 * 
 * @see org.springframework.batch.repeat.RepeatOperations#iterate(org.springframework.batch.repeat.RepeatCallback)
 */
@Override
public RepeatStatus iterate(RepeatCallback callback) {

    RepeatContext outer = RepeatSynchronizationManager.getContext();

    RepeatStatus result = RepeatStatus.CONTINUABLE;
    try {
        // This works with an asynchronous TaskExecutor: the
        // interceptors have to wait for the child processes.
        result = executeInternal(callback);
    } finally {
        RepeatSynchronizationManager.clear();
        if (outer != null) {
            RepeatSynchronizationManager.register(outer);
        }
    }

    return result;
}

From source file:org.springframework.batch.repeat.support.RepeatTemplate.java

/**
 * Internal convenience method to loop over interceptors and batch
 * callbacks./*w  ww .  j  a  v  a2 s.c om*/
 * 
 * @param callback the callback to process each element of the loop.
 * 
 * @return the aggregate of {@link RepeatTemplate#canContinue(RepeatStatus)}
 * for all the results from the callback.
 * 
 */
private RepeatStatus executeInternal(final RepeatCallback callback) {

    // Reset the termination policy if there is one...
    RepeatContext context = start();

    // Make sure if we are already marked complete before we start then no
    // processing takes place.
    boolean running = !isMarkedComplete(context);

    for (int i = 0; i < listeners.length; i++) {
        RepeatListener interceptor = listeners[i];
        interceptor.open(context);
        running = running && !isMarkedComplete(context);
        if (!running)
            break;
    }

    // Return value, default is to allow continued processing.
    RepeatStatus result = RepeatStatus.CONTINUABLE;

    RepeatInternalState state = createInternalState(context);
    // This is the list of exceptions thrown by all active callbacks
    Collection<Throwable> throwables = state.getThrowables();
    // Keep a separate list of exceptions we handled that need to be
    // rethrown
    Collection<Throwable> deferred = new ArrayList<Throwable>();

    try {

        while (running) {

            /*
             * Run the before interceptors here, not in the task executor so
             * that they all happen in the same thread - it's easier for
             * tracking batch status, amongst other things.
             */
            for (int i = 0; i < listeners.length; i++) {
                RepeatListener interceptor = listeners[i];
                interceptor.before(context);
                // Allow before interceptors to veto the batch by setting
                // flag.
                running = running && !isMarkedComplete(context);
            }

            // Check that we are still running (should always be true) ...
            if (running) {

                try {

                    result = getNextResult(context, callback, state);
                    executeAfterInterceptors(context, result);

                } catch (Throwable throwable) {
                    doHandle(throwable, context, deferred);
                }

                // N.B. the order may be important here:
                if (isComplete(context, result) || isMarkedComplete(context) || !deferred.isEmpty()) {
                    running = false;
                }

            }

        }

        result = result.and(waitForResults(state));
        for (Throwable throwable : throwables) {
            doHandle(throwable, context, deferred);
        }

        // Explicitly drop any references to internal state...
        state = null;

    }
    /*
     * No need for explicit catch here - if the business processing threw an
     * exception it was already handled by the helper methods. An exception
     * here is necessarily fatal.
     */
    finally {

        try {

            if (!deferred.isEmpty()) {
                Throwable throwable = deferred.iterator().next();
                if (logger.isDebugEnabled()) {
                    logger.debug("Handling fatal exception explicitly (rethrowing first of " + deferred.size()
                            + "): " + throwable.getClass().getName() + ": " + throwable.getMessage());
                }
                rethrow(throwable);
            }

        } finally {

            try {
                for (int i = listeners.length; i-- > 0;) {
                    RepeatListener interceptor = listeners[i];
                    interceptor.close(context);
                }
            } finally {
                context.close();
            }

        }

    }

    return result;

}

From source file:org.springframework.batch.repeat.support.TaskExecutorRepeatTemplateBulkAsynchronousTests.java

@Test
public void testErrorThrownByCallback() throws Exception {

    callback = new RepeatCallback() {

        private volatile AtomicInteger count = new AtomicInteger(0);

        @Override/*from  w ww  .j a v  a 2 s.  c om*/
        public RepeatStatus doInIteration(RepeatContext context) throws Exception {
            int position = count.incrementAndGet();

            if (position == 4) {
                throw new OutOfMemoryError("Planned");
            } else {
                return RepeatStatus.CONTINUABLE;
            }
        }
    };

    template.setCompletionPolicy(new SimpleCompletionPolicy(10));

    try {
        template.iterate(callback);
        fail("Expected planned exception");
    } catch (OutOfMemoryError oome) {
        assertEquals("Planned", oome.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
        fail("Wrong exception was thrown: " + e);
    }
}