Search in sources :

Example 1 with RetryException

use of org.springframework.retry.RetryException in project spring-retry by spring-projects.

the class StatefulRecoveryRetryTests method testCacheCapacity.

@Test
public void testCacheCapacity() throws Throwable {
    this.retryTemplate.setRetryPolicy(new SimpleRetryPolicy(1));
    this.retryTemplate.setRetryContextCache(new MapRetryContextCache(1));
    RetryCallback<Object, Exception> callback = new RetryCallback<Object, Exception>() {

        @Override
        public Object doWithRetry(RetryContext context) throws Exception {
            StatefulRecoveryRetryTests.this.count++;
            throw new RuntimeException("Barf!");
        }
    };
    try {
        this.retryTemplate.execute(callback, new DefaultRetryState("foo"));
        fail("Expected RuntimeException");
    } catch (RuntimeException e) {
        assertEquals("Barf!", e.getMessage());
    }
    try {
        this.retryTemplate.execute(callback, new DefaultRetryState("bar"));
        fail("Expected RetryException");
    } catch (RetryException e) {
        String message = e.getMessage();
        assertTrue("Message does not contain 'capacity': " + message, message.indexOf("capacity") >= 0);
    }
}
Also used : MapRetryContextCache(org.springframework.retry.policy.MapRetryContextCache) RetryContext(org.springframework.retry.RetryContext) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) RetryException(org.springframework.retry.RetryException) DataAccessException(org.springframework.dao.DataAccessException) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) RetryException(org.springframework.retry.RetryException) RetryCallback(org.springframework.retry.RetryCallback) Test(org.junit.Test)

Example 2 with RetryException

use of org.springframework.retry.RetryException in project spring-retry by spring-projects.

the class StatefulRecoveryRetryTests method testKeyGeneratorNotConsistentAfterFailure.

@Test
public void testKeyGeneratorNotConsistentAfterFailure() throws Throwable {
    RetryPolicy retryPolicy = new SimpleRetryPolicy(3);
    this.retryTemplate.setRetryPolicy(retryPolicy);
    final StringHolder item = new StringHolder("bar");
    RetryState state = new DefaultRetryState(item);
    RetryCallback<StringHolder, Exception> callback = new RetryCallback<StringHolder, Exception>() {

        @Override
        public StringHolder doWithRetry(RetryContext context) throws Exception {
            // This simulates what happens if someone uses a primary key
            // for hashCode and equals and then relies on default key
            // generator
            item.string = item.string + (StatefulRecoveryRetryTests.this.count++);
            throw new RuntimeException("Barf!");
        }
    };
    try {
        this.retryTemplate.execute(callback, state);
        fail("Expected RuntimeException");
    } catch (RuntimeException ex) {
        String message = ex.getMessage();
        assertEquals("Barf!", message);
    }
    // item already...
    try {
        this.retryTemplate.execute(callback, state);
        fail("Expected RetryException");
    } catch (RetryException ex) {
        String message = ex.getMessage();
        assertTrue("Message doesn't contain 'inconsistent': " + message, message.contains("inconsistent"));
    }
    RetryContext context = this.retryTemplate.open(retryPolicy, state);
    // True after exhausted - the history is reset...
    assertEquals(0, context.getRetryCount());
}
Also used : RetryContext(org.springframework.retry.RetryContext) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) RetryException(org.springframework.retry.RetryException) SimpleRetryPolicy(org.springframework.retry.policy.SimpleRetryPolicy) NeverRetryPolicy(org.springframework.retry.policy.NeverRetryPolicy) RetryPolicy(org.springframework.retry.RetryPolicy) DataAccessException(org.springframework.dao.DataAccessException) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) RetryException(org.springframework.retry.RetryException) RetryState(org.springframework.retry.RetryState) RetryCallback(org.springframework.retry.RetryCallback) Test(org.junit.Test)

Example 3 with RetryException

use of org.springframework.retry.RetryException in project spring-batch by spring-projects.

the class FaultTolerantChunkProcessor method transform.

@Override
protected Chunk<O> transform(final StepContribution contribution, Chunk<I> inputs) throws Exception {
    Chunk<O> outputs = new Chunk<>();
    @SuppressWarnings("unchecked") final UserData<O> data = (UserData<O>) inputs.getUserData();
    final Chunk<O> cache = data.getOutputs();
    final Iterator<O> cacheIterator = cache.isEmpty() ? null : new ArrayList<>(cache.getItems()).iterator();
    for (final Chunk<I>.ChunkIterator iterator = inputs.iterator(); iterator.hasNext(); ) {
        final I item = iterator.next();
        RetryCallback<O, Exception> retryCallback = new RetryCallback<O, Exception>() {

            @Override
            public O doWithRetry(RetryContext context) throws Exception {
                Timer.Sample sample = BatchMetrics.createTimerSample();
                String status = BatchMetrics.STATUS_SUCCESS;
                O output = null;
                try {
                    O cached = (cacheIterator != null && cacheIterator.hasNext()) ? cacheIterator.next() : null;
                    if (cached != null && !processorTransactional) {
                        output = cached;
                    } else {
                        output = doProcess(item);
                        if (output == null) {
                            data.incrementFilterCount();
                        } else if (!processorTransactional && !data.scanning()) {
                            cache.add(output);
                        }
                    }
                } catch (Exception e) {
                    status = BatchMetrics.STATUS_FAILURE;
                    if (rollbackClassifier.classify(e)) {
                        // allows us to continue
                        throw e;
                    } else if (shouldSkip(itemProcessSkipPolicy, e, contribution.getStepSkipCount())) {
                        // If we are not re-throwing then we should check if
                        // this is skippable
                        contribution.incrementProcessSkipCount();
                        logger.debug("Skipping after failed process with no rollback", e);
                        // If not re-throwing then the listener will not be
                        // called in next chunk.
                        callProcessSkipListener(item, e);
                    } else {
                        // back if we are also not allowed to skip
                        throw new NonSkippableProcessException("Non-skippable exception in processor.  Make sure any exceptions that do not cause a rollback are skippable.", e);
                    }
                } finally {
                    stopTimer(sample, contribution.getStepExecution(), "item.process", status, "Item processing");
                }
                if (output == null) {
                    // No need to re-process filtered items
                    iterator.remove();
                }
                return output;
            }
        };
        RecoveryCallback<O> recoveryCallback = new RecoveryCallback<O>() {

            @Override
            public O recover(RetryContext context) throws Exception {
                Throwable e = context.getLastThrowable();
                if (shouldSkip(itemProcessSkipPolicy, e, contribution.getStepSkipCount())) {
                    iterator.remove(e);
                    contribution.incrementProcessSkipCount();
                    logger.debug("Skipping after failed process", e);
                    return null;
                } else {
                    if (rollbackClassifier.classify(e)) {
                        // allows us to continue
                        throw new RetryException("Non-skippable exception in recoverer while processing", e);
                    }
                    iterator.remove(e);
                    return null;
                }
            }
        };
        O output = batchRetryTemplate.execute(retryCallback, recoveryCallback, new DefaultRetryState(getInputKey(item), rollbackClassifier));
        if (output != null) {
            outputs.add(output);
        }
        /*
			 * We only want to process the first item if there is a scan for a
			 * failed item.
			 */
        if (data.scanning()) {
            while (cacheIterator != null && cacheIterator.hasNext()) {
                outputs.add(cacheIterator.next());
            }
            // Only process the first item if scanning
            break;
        }
    }
    return outputs;
}
Also used : RecoveryCallback(org.springframework.retry.RecoveryCallback) NonSkippableProcessException(org.springframework.batch.core.step.skip.NonSkippableProcessException) DefaultRetryState(org.springframework.retry.support.DefaultRetryState) RetryContext(org.springframework.retry.RetryContext) ArrayList(java.util.ArrayList) RetryException(org.springframework.retry.RetryException) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) SkipListenerFailedException(org.springframework.batch.core.step.skip.SkipListenerFailedException) RetryException(org.springframework.retry.RetryException) NonSkippableProcessException(org.springframework.batch.core.step.skip.NonSkippableProcessException) StepListenerFailedException(org.springframework.batch.core.listener.StepListenerFailedException) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) SkipLimitExceededException(org.springframework.batch.core.step.skip.SkipLimitExceededException) Timer(io.micrometer.core.instrument.Timer) RetryCallback(org.springframework.retry.RetryCallback)

Example 4 with RetryException

use of org.springframework.retry.RetryException in project spring-batch by spring-projects.

the class FaultTolerantChunkProcessor method checkSkipPolicy.

private void checkSkipPolicy(Chunk<I>.ChunkIterator inputIterator, Chunk<O>.ChunkIterator outputIterator, Throwable e, StepContribution contribution, boolean recovery) throws Exception {
    logger.debug("Checking skip policy after failed write");
    if (shouldSkip(itemWriteSkipPolicy, e, contribution.getStepSkipCount())) {
        contribution.incrementWriteSkipCount();
        inputIterator.remove();
        outputIterator.remove(e);
        logger.debug("Skipping after failed write", e);
    } else {
        if (recovery) {
            // Only if already recovering should we check skip policy
            throw new RetryException("Non-skippable exception in recoverer", e);
        } else {
            if (e instanceof Exception) {
                throw (Exception) e;
            } else if (e instanceof Error) {
                throw (Error) e;
            } else {
                throw new RetryException("Non-skippable throwable in recoverer", e);
            }
        }
    }
}
Also used : RetryException(org.springframework.retry.RetryException) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) SkipListenerFailedException(org.springframework.batch.core.step.skip.SkipListenerFailedException) RetryException(org.springframework.retry.RetryException) NonSkippableProcessException(org.springframework.batch.core.step.skip.NonSkippableProcessException) StepListenerFailedException(org.springframework.batch.core.listener.StepListenerFailedException) ExhaustedRetryException(org.springframework.retry.ExhaustedRetryException) SkipLimitExceededException(org.springframework.batch.core.step.skip.SkipLimitExceededException)

Example 5 with RetryException

use of org.springframework.retry.RetryException in project api-layer by zowe.

the class InstanceInitializeService method retrieveAndRegisterAllInstancesWithCatalog.

/**
 * Initialise the API Catalog with all current running instances
 * The API Catalog itself must be UP before checking all other instances
 * If the catalog is not up, or if the fetch fails, then wait for a defined period and retry up to a max of 5 times
 *
 * @throws CannotRegisterServiceException if the fetch fails or the catalog is not registered with the discovery
 */
@Retryable(value = { RetryException.class }, exclude = CannotRegisterServiceException.class, maxAttempts = 5, backoff = @Backoff(delayExpression = "#{${apiml.service-registry.serviceFetchDelayInMillis}}"))
public void retrieveAndRegisterAllInstancesWithCatalog() throws CannotRegisterServiceException {
    log.info("Initialising API Catalog with Discovery services.");
    try {
        String serviceId = CoreService.API_CATALOG.getServiceId();
        InstanceInfo apiCatalogInstance = instanceRetrievalService.getInstanceInfo(serviceId);
        if (apiCatalogInstance == null) {
            String msg = "API Catalog Instance not retrieved from Discovery service";
            log.debug(msg);
            throw new RetryException(msg);
        } else {
            log.info("API Catalog instance found, retrieving all services.");
            getAllInstances(apiCatalogInstance);
            instanceRefreshService.start();
        }
    } catch (InstanceInitializationException | GatewayNotAvailableException e) {
        throw new RetryException(e.getMessage());
    } catch (Exception e) {
        String msg = "An unexpected exception occurred when trying to retrieve API Catalog instance from Discovery service";
        apimlLog.log("org.zowe.apiml.apicatalog.initializeAborted", e.getMessage());
        throw new CannotRegisterServiceException(msg, e);
    }
}
Also used : GatewayNotAvailableException(org.zowe.apiml.product.gateway.GatewayNotAvailableException) RetryException(org.springframework.retry.RetryException) InstanceInfo(com.netflix.appinfo.InstanceInfo) CannotRegisterServiceException(org.zowe.apiml.product.registry.CannotRegisterServiceException) InstanceInitializationException(org.zowe.apiml.product.instance.InstanceInitializationException) GatewayNotAvailableException(org.zowe.apiml.product.gateway.GatewayNotAvailableException) RetryException(org.springframework.retry.RetryException) InstanceInitializationException(org.zowe.apiml.product.instance.InstanceInitializationException) CannotRegisterServiceException(org.zowe.apiml.product.registry.CannotRegisterServiceException) Retryable(org.springframework.retry.annotation.Retryable)

Aggregations

RetryException (org.springframework.retry.RetryException)12 ExhaustedRetryException (org.springframework.retry.ExhaustedRetryException)6 RetryContext (org.springframework.retry.RetryContext)5 SimpleRetryPolicy (org.springframework.retry.policy.SimpleRetryPolicy)4 RetryCallback (org.springframework.retry.RetryCallback)3 Retryable (org.springframework.retry.annotation.Retryable)3 Timer (io.micrometer.core.instrument.Timer)2 ArrayList (java.util.ArrayList)2 AtomicReference (java.util.concurrent.atomic.AtomicReference)2 Test (org.junit.Test)2 StepListenerFailedException (org.springframework.batch.core.listener.StepListenerFailedException)2 NonSkippableProcessException (org.springframework.batch.core.step.skip.NonSkippableProcessException)2 SkipLimitExceededException (org.springframework.batch.core.step.skip.SkipLimitExceededException)2 SkipListenerFailedException (org.springframework.batch.core.step.skip.SkipListenerFailedException)2 DataAccessException (org.springframework.dao.DataAccessException)2 GatewayNotAvailableException (org.zowe.apiml.product.gateway.GatewayNotAvailableException)2 InstanceInitializationException (org.zowe.apiml.product.instance.InstanceInitializationException)2 CannotRegisterServiceException (org.zowe.apiml.product.registry.CannotRegisterServiceException)2 EnableMFADeviceResult (com.amazonaws.services.identitymanagement.model.EnableMFADeviceResult)1 OTPAccessCode (com.baiyi.opscloud.otp.model.OTPAccessCode)1