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);
}
}
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());
}
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;
}
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);
}
}
}
}
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);
}
}
Aggregations