Java Code Examples for org.springframework.retry.RetryCallback

The following examples show how to use org.springframework.retry.RetryCallback. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: retry   Source File: SimpleDemo.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    RetryTemplate template = new RetryTemplate();

    // 策略
    SimpleRetryPolicy policy = new SimpleRetryPolicy();
    policy.setMaxAttempts(2);
    template.setRetryPolicy(policy);

    String result = template.execute(
            new RetryCallback<String, Exception>() {
                @Override
                public String doWithRetry(RetryContext arg0) {
                    throw new NullPointerException();
                }
            }
            ,
            new RecoveryCallback<String>() {
                @Override
                public String recover(RetryContext context) {
                    return "recovery callback";
                }
            }
    );

    LOGGER.info("result: {}", result);
}
 
Example 2
@Test(expected = TerminatedRetryException.class)
public void retryListenerTestNoRetry() throws Throwable {
	HttpRequest request = mock(HttpRequest.class);
	when(request.getURI()).thenReturn(new URI("http://noRetry"));
	LoadBalancedRetryPolicy policy = mock(LoadBalancedRetryPolicy.class);
	MyBackOffPolicy backOffPolicy = new MyBackOffPolicy();
	this.lbProperties.setEnabled(true);
	RetryListener myRetryListener = new RetryListenerSupport() {
		@Override
		public <T, E extends Throwable> boolean open(RetryContext context,
				RetryCallback<T, E> callback) {
			return false;
		}
	};
	RetryLoadBalancerInterceptor interceptor = new RetryLoadBalancerInterceptor(
			this.client, this.lbProperties, this.lbRequestFactory,
			new MyLoadBalancedRetryFactory(policy, backOffPolicy,
					new RetryListener[] { myRetryListener }));
	ClientHttpRequestExecution execution = mock(ClientHttpRequestExecution.class);
	interceptor.intercept(request, new byte[] {}, execution);
}
 
Example 3
@Test
void testInterruptFailingTries() throws Exception {
  Future<Client> result =
      executorService.submit(
          () -> {
            RetryCallback<Client, RuntimeException> fail =
                c -> {
                  throw new MolgenisDataException();
                };
            return retryTemplate.execute(fail);
          });

  result.cancel(true);
  try {
    result.get(100, TimeUnit.MILLISECONDS);
    fail("Should throw cancellation exception!");
  } catch (CancellationException ignore) {
  }
  assertTrue(result.isDone());
  assertTrue(result.isCancelled());
}
 
Example 4
Source Project: mojito   Source File: AssetMappingService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Creates {@link TMTextUnit} for {@link AssetTextUnit}s that don't have a
 * MD5 matches.
 *
 * @param assetExtractionId a valid {@link AssetExtraction#id}
 * @param tmId              a valid {@link TM#id}
 * @param assetId           a valid {@link Asset#id}
 * @return the newly created {@link TMTextUnit}s
 */
protected List<TMTextUnit> createTMTextUnitForUnmappedAssetTextUnitsWithRetry(final Long assetExtractionId, final Long tmId, final Long assetId, User createdByUser) {
    return retryTemplate.execute(new RetryCallback<List<TMTextUnit>, DataIntegrityViolationException>() {
        @Override
        public List<TMTextUnit> doWithRetry(RetryContext context) throws DataIntegrityViolationException {

            if (context.getRetryCount() > 0) {
                long mapExactMatches = mapExactMatches(assetExtractionId, tmId, assetId);
                logger.error("Assume concurrent modification happened, perform remapping: {}", mapExactMatches);
            }

            return createTMTextUnitForUnmappedAssetTextUnits(createdByUser, assetExtractionId, tmId, assetId);
        }
    });
}
 
Example 5
Source Project: mojito   Source File: AssetExtractionService.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Marks the provided asset extraction as current extraction for the branch.
 * <p>
 * Make the function {@link Retryable} since this can have concurrent access issue when multiple thread trying to save
 * the active asset extraction at the same time. It is not important which one wins last since in real usage
 * that should not really happen, it is an edge case and the code just need to be safe.
 *
 * @param assetExtraction
 */
private void markAssetExtractionForBranch(final AssetExtraction assetExtraction) {

    final Asset asset = assetExtraction.getAsset();
    final Branch branch = assetExtraction.getAssetContent().getBranch();

    logger.debug("markAssetExtractionForBranch, assetId: {}, branch: {}", asset.getId(), branch.getName());

    retryTemplate.execute(new RetryCallback<AssetExtractionByBranch, DataIntegrityViolationException>() {
        @Override
        public AssetExtractionByBranch doWithRetry(RetryContext context) throws DataIntegrityViolationException {

            if (context.getRetryCount() > 0) {
                logger.debug("Concurrent modification happened when saving the active asset extraction, retry");
            }

            AssetExtractionByBranch assetExtractionByBranch = assetExtractionByBranchRepository.findByAssetAndBranch(assetExtraction.getAsset(), branch);

            if (assetExtractionByBranch == null) {
                assetExtractionByBranch = new AssetExtractionByBranch();
                assetExtractionByBranch.setAsset(assetExtraction.getAsset());
                assetExtractionByBranch.setBranch(branch);
            }

            assetExtractionByBranch.setAssetExtraction(assetExtraction);
            assetExtractionByBranch.setDeleted(false);

            assetExtractionByBranch = assetExtractionByBranchRepository.save(assetExtractionByBranch);

            return assetExtractionByBranch;
        }
    });
}
 
Example 6
Source Project: hawkbit   Source File: JpaDeploymentManagement.java    License: Eclipse Public License 1.0 5 votes vote down vote up
private DistributionSetAssignmentResult assignDistributionSetToTargetsWithRetry(final Long dsID,
        final Collection<TargetWithActionType> targetsWithActionType, final String actionMessage,
        final AbstractDsAssignmentStrategy assignmentStrategy) {
    final RetryCallback<DistributionSetAssignmentResult, ConcurrencyFailureException> retryCallback = retryContext -> assignDistributionSetToTargets(
            dsID, targetsWithActionType, actionMessage, assignmentStrategy);
    return retryTemplate.execute(retryCallback);
}
 
Example 7
@Override
public <T, E extends Throwable> boolean open(RetryContext context,
		RetryCallback<T, E> callback) {
	if (DefaultPollableMessageSource.this.recoveryCallback != null) {
		attributesHolder.set(context);
	}
	return true;
}
 
Example 8
Source Project: spring-cloud-stream   Source File: TestChannelBinder.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public <T, E extends Throwable> boolean open(RetryContext context,
		RetryCallback<T, E> callback) {
	if (IntegrationBinderInboundChannelAdapter.this.recoveryCallback != null) {
		attributesHolder.set(context);
	}
	return true;
}
 
Example 9
Source Project: batchers   Source File: CallWebserviceProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private RetryCallback<Void, TaxWebServiceException> doWebserviceCallWithRetryCallback(TaxCalculation taxCalculation) {
    return new RetryCallback<Void, TaxWebServiceException>() {
        @Override
        public Void doWithRetry(RetryContext context) throws TaxWebServiceException {
            taxPaymentWebService.doWebserviceCallToTaxService(taxCalculation.getEmployee(), taxCalculation.getTax());
            return null;
        }
    };
}
 
Example 10
Source Project: api-layer   Source File: AbortingRetryListener.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
    return true;
}
 
Example 11
Source Project: api-layer   Source File: AbortingRetryListener.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
    // do nothing
}
 
Example 12
Source Project: api-layer   Source File: AbortingRetryListener.java    License: Eclipse Public License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
    if (throwable instanceof RequestAbortException) {
        context.setExhaustedOnly();
    }
}
 
Example 13
@Override
public <T, E extends Throwable> boolean open(RetryContext context,
		RetryCallback<T, E> callback) {
	return true;
}
 
Example 14
@Override
public <T, E extends Throwable> void close(RetryContext context,
		RetryCallback<T, E> callback, Throwable throwable) {
}
 
Example 15
@Override
public <T, E extends Throwable> void onError(RetryContext context,
		RetryCallback<T, E> callback, Throwable throwable) {

}
 
Example 16
Source Project: oneops   Source File: CMSClient.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
    logger.info("Remote call failed, Will retry (count = " + context.getRetryCount()+" ) exception :" +throwable.getClass().getSimpleName());
    super.onError(context, callback, throwable);
}
 
Example 17
Source Project: oneops   Source File: CMSClient.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> void close(final RetryContext context, final RetryCallback<T, E> callback, final Throwable throwable) {
    if (throwable != null) {
        logger.info("Final  retry attempt failed,  ", throwable);
    }
}
 
Example 18
@Override
public <T, E extends Throwable> void close(RetryContext context,
		RetryCallback<T, E> callback, Throwable throwable) {
	attributesHolder.remove();
}
 
Example 19
@Override
public <T, E extends Throwable> void onError(RetryContext context,
		RetryCallback<T, E> callback, Throwable throwable) {
	// Empty
}
 
Example 20
Source Project: spring-cloud-stream   Source File: TestChannelBinder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> void close(RetryContext context,
		RetryCallback<T, E> callback, Throwable throwable) {
	attributesHolder.remove();
}
 
Example 21
Source Project: spring-cloud-stream   Source File: TestChannelBinder.java    License: Apache License 2.0 4 votes vote down vote up
@Override
public <T, E extends Throwable> void onError(RetryContext context,
		RetryCallback<T, E> callback, Throwable throwable) {
	// Empty
}
 
Example 22
@Override
public <T, E extends Throwable> void onError(RetryContext retryContext,
		RetryCallback<T, E> retryCallback, Throwable throwable) {
	this.onError++;
}
 
Example 23
Source Project: tutorials   Source File: DefaultListenerSupport.java    License: MIT License 4 votes vote down vote up
@Override
public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
    logger.info("onClose");
    super.close(context, callback, throwable);
}
 
Example 24
Source Project: tutorials   Source File: DefaultListenerSupport.java    License: MIT License 4 votes vote down vote up
@Override
public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
    logger.info("onError");
    super.onError(context, callback, throwable);
}
 
Example 25
Source Project: tutorials   Source File: DefaultListenerSupport.java    License: MIT License 4 votes vote down vote up
@Override
public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
    logger.info("onOpen");
    return super.open(context, callback);
}
 
Example 26
Source Project: OTX-Java-SDK   Source File: OTXConnection.java    License: Apache License 2.0 3 votes vote down vote up
private <T> T executeGetRequest(final OTXEndpoints subscribed, final Map<OTXEndpointParameters, ?> endpointParametersMap, final Class<T> classType) throws MalformedURLException, URISyntaxException {

        final URI url = buildURI(subscribed, endpointParametersMap);

        return  retryTemplate.execute(new RetryCallback<T, RestClientException>() {

            public T doWithRetry(RetryContext context) {
                // Do stuff that might fail, e.g. webservice operation
                return restTemplate.getForObject(url, classType);
            }

        });
    }