Java Code Examples for org.springframework.retry.support.RetryTemplate#setRetryPolicy()

The following examples show how to use org.springframework.retry.support.RetryTemplate#setRetryPolicy() . 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 File: FeatureFileUtilsImpl.java    From IridiumApplicationTesting with MIT License 8 votes vote down vote up
private List<File> processRemoteUrl(@NotNull final String path) throws IOException {
	final File copy = File.createTempFile("webapptester", ".feature");

	try {
		final RetryTemplate template = new RetryTemplate();
		final SimpleRetryPolicy policy = new SimpleRetryPolicy();
		policy.setMaxAttempts(Constants.URL_COPY_RETRIES);
		template.setRetryPolicy(policy);
		template.execute(context -> {
			FileUtils.copyURLToFile(new URL(path), copy);
			return null;
		});

		return Arrays.asList(copy);
	} catch (final FileNotFoundException ex) {
		/*
			Don't leave an empty file hanging around
		 */
		FileUtils.deleteQuietly(copy);
		throw new RemoteFeatureException("The remote file could not be downloaded."
			+ " Either the URL was invalid, or the path was actually supposed to reference a"
			+ " local file but that file could not be found an so was assumed to be a URL.",  ex);
	}
}
 
Example 2
Source File: Application.java    From mojito with Apache License 2.0 6 votes vote down vote up
@Bean
public RetryTemplate retryTemplate() {
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);

    ExponentialRandomBackOffPolicy exponentialRandomBackOffPolicy = new ExponentialRandomBackOffPolicy();
    exponentialRandomBackOffPolicy.setInitialInterval(10);
    exponentialRandomBackOffPolicy.setMultiplier(3);
    exponentialRandomBackOffPolicy.setMaxInterval(5000);

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(exponentialRandomBackOffPolicy);
    template.setThrowLastExceptionOnExhausted(true);

    return template;
}
 
Example 3
Source File: HttpBlockchainEventBroadcasterTest.java    From eventeum with Apache License 2.0 6 votes vote down vote up
@Before
public void init() {
    final HttpBroadcasterSettings settings = new HttpBroadcasterSettings();
    settings.setBlockEventsUrl("http://localhost:8082/consumer/block-event");
    settings.setContractEventsUrl("http://localhost:8082/consumer/contract-event");

    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(3000l);
    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(3);
    retryTemplate.setRetryPolicy(retryPolicy);

    underTest = new HttpBlockchainEventBroadcaster(settings, retryTemplate);
}
 
Example 4
Source File: InteractiveQueryService.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
/**
 * Retrieve and return a queryable store by name created in the application.
 * @param storeName name of the queryable store
 * @param storeType type of the queryable store
 * @param <T> generic queryable store
 * @return queryable store.
 */
public <T> T getQueryableStore(String storeName, QueryableStoreType<T> storeType) {

	RetryTemplate retryTemplate = new RetryTemplate();

	KafkaStreamsBinderConfigurationProperties.StateStoreRetry stateStoreRetry = this.binderConfigurationProperties.getStateStoreRetry();
	RetryPolicy retryPolicy = new SimpleRetryPolicy(stateStoreRetry.getMaxAttempts());
	FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
	backOffPolicy.setBackOffPeriod(stateStoreRetry.getBackoffPeriod());

	retryTemplate.setBackOffPolicy(backOffPolicy);
	retryTemplate.setRetryPolicy(retryPolicy);

	return retryTemplate.execute(context -> {
		T store = null;

		final Set<KafkaStreams> kafkaStreams = InteractiveQueryService.this.kafkaStreamsRegistry.getKafkaStreams();
		final Iterator<KafkaStreams> iterator = kafkaStreams.iterator();
		Throwable throwable = null;
		while (iterator.hasNext()) {
			try {
				store = iterator.next().store(storeName, storeType);
			}
			catch (InvalidStateStoreException e) {
				// pass through..
				throwable = e;
			}
		}
		if (store != null) {
			return store;
		}
		throw new IllegalStateException("Error when retrieving state store: j " + storeName, throwable);
	});
}
 
Example 5
Source File: RetryLoadBalancerInterceptor.java    From spring-cloud-commons with Apache License 2.0 6 votes vote down vote up
private RetryTemplate createRetryTemplate(String serviceName, HttpRequest request,
		LoadBalancedRetryPolicy retryPolicy) {
	RetryTemplate template = new RetryTemplate();
	BackOffPolicy backOffPolicy = this.lbRetryFactory
			.createBackOffPolicy(serviceName);
	template.setBackOffPolicy(
			backOffPolicy == null ? new NoBackOffPolicy() : backOffPolicy);
	template.setThrowLastExceptionOnExhausted(true);
	RetryListener[] retryListeners = this.lbRetryFactory
			.createRetryListeners(serviceName);
	if (retryListeners != null && retryListeners.length != 0) {
		template.setListeners(retryListeners);
	}
	template.setRetryPolicy(!this.lbProperties.isEnabled() || retryPolicy == null
			? new NeverRetryPolicy() : new InterceptorRetryPolicy(request,
					retryPolicy, this.loadBalancer, serviceName));
	return template;
}
 
Example 6
Source File: KafkaTopicProvisioner.java    From spring-cloud-stream-binder-kafka with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
	if (this.metadataRetryOperations == null) {
		RetryTemplate retryTemplate = new RetryTemplate();

		SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
		simpleRetryPolicy.setMaxAttempts(10);
		retryTemplate.setRetryPolicy(simpleRetryPolicy);

		ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
		backOffPolicy.setInitialInterval(100);
		backOffPolicy.setMultiplier(2);
		backOffPolicy.setMaxInterval(1000);
		retryTemplate.setBackOffPolicy(backOffPolicy);
		this.metadataRetryOperations = retryTemplate;
	}
}
 
Example 7
Source File: FileContentRetrieval.java    From IridiumApplicationTesting with MIT License 6 votes vote down vote up
private String retrieveStringFromRemoteFile(@NotNull final String remoteFileName)  {
	checkArgument(StringUtils.isNoneBlank(remoteFileName));

	File copy = null;
	try {
		copy = File.createTempFile("capabilities", ".tmp");

		final File finalCopy = copy;
		final RetryTemplate template = new RetryTemplate();
		final SimpleRetryPolicy policy = new SimpleRetryPolicy();
		policy.setMaxAttempts(Constants.URL_COPY_RETRIES);
		template.setRetryPolicy(policy);
		template.execute(context -> {
			FileUtils.copyURLToFile(new URL(remoteFileName), finalCopy, TIMEOUT, TIMEOUT);
			return null;
		});

		return retrieveStringFromLocalFile(copy.getAbsolutePath());
	} catch (final IOException ex) {
		throw new ConfigurationException(ex);
	} finally {
		if (copy != null) {
			FileUtils.deleteQuietly(copy);
		}
	}
}
 
Example 8
Source File: InitializrStatsAutoConfiguration.java    From initializr with Apache License 2.0 5 votes vote down vote up
@Bean
@ConditionalOnMissingBean(name = "statsRetryTemplate")
RetryTemplate statsRetryTemplate() {
	RetryTemplate retryTemplate = new RetryTemplate();
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(3000L);
	backOffPolicy.setMultiplier(3);
	SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(this.statsProperties.getElastic().getMaxAttempts(),
			Collections.singletonMap(Exception.class, true));
	retryTemplate.setBackOffPolicy(backOffPolicy);
	retryTemplate.setRetryPolicy(retryPolicy);
	return retryTemplate;
}
 
Example 9
Source File: FieldValueCounterSinkStoreConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryOperations retryOperations() {
	RetryTemplate retryTemplate = new RetryTemplate();
	retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3, Collections.<Class<? extends Throwable>, Boolean>singletonMap(RedisConnectionFailureException.class, true)));
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(1000L);
	backOffPolicy.setMaxInterval(1000L);
	backOffPolicy.setMultiplier(2);
	retryTemplate.setBackOffPolicy(backOffPolicy);
	return retryTemplate;
}
 
Example 10
Source File: JobStatusWebhookEventListener.java    From piper with Apache License 2.0 5 votes vote down vote up
private RetryTemplate createRetryTemplate (Accessor aWebhook) {
  MapObject retryParams = aWebhook.get("retry",MapObject.class,new MapObject());
  RetryTemplate retryTemplate = new RetryTemplate();
  ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
  backOffPolicy.setInitialInterval(retryParams.getDuration("initialInterval", "2s").toMillis());
  backOffPolicy.setMaxInterval(retryParams.getDuration("maxInterval", "30s").toMillis());
  backOffPolicy.setMultiplier(retryParams.getDouble("multiplier",2.0));
  retryTemplate.setBackOffPolicy(backOffPolicy);
  SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
  retryPolicy.setMaxAttempts(retryParams.getInteger("maxAttempts", 5));
  retryTemplate.setRetryPolicy(retryPolicy);
  return retryTemplate;
}
 
Example 11
Source File: AggregateCounterSinkStoreConfiguration.java    From spring-cloud-stream-app-starters with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryOperations retryOperations() {
	RetryTemplate retryTemplate = new RetryTemplate();
	retryTemplate.setRetryPolicy(new SimpleRetryPolicy(3,
			Collections.<Class<? extends Throwable>, Boolean>singletonMap(RedisConnectionFailureException.class, true)));
	ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
	backOffPolicy.setInitialInterval(1000L);
	backOffPolicy.setMaxInterval(1000L);
	backOffPolicy.setMultiplier(2);
	retryTemplate.setBackOffPolicy(backOffPolicy);
	return retryTemplate;
}
 
Example 12
Source File: JpaDeploymentManagement.java    From hawkbit with Eclipse Public License 1.0 5 votes vote down vote up
private static RetryTemplate createRetryTemplate() {
    final RetryTemplate template = new RetryTemplate();

    final FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(Constants.TX_RT_DELAY);
    template.setBackOffPolicy(backOffPolicy);

    final SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(Constants.TX_RT_MAX,
            Collections.singletonMap(ConcurrencyFailureException.class, true));
    template.setRetryPolicy(retryPolicy);

    return template;
}
 
Example 13
Source File: RetryConfig.java    From batchers with Apache License 2.0 5 votes vote down vote up
public RetryTemplate createRetryTemplate() {
    Map<Class<? extends Throwable>, Boolean> exceptions = new HashMap<>();
    exceptions.put(TaxWebServiceNonFatalException.class, true);

    RetryTemplate template = new RetryTemplate();
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(maxAttempts, exceptions);
    template.setRetryPolicy(retryPolicy);

    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(initialInterval);
    template.setBackOffPolicy(backOffPolicy);

    return template;
}
 
Example 14
Source File: AmqpContextConfig.java    From sinavi-jfw with Apache License 2.0 5 votes vote down vote up
/**
 * {@link RetryTemplate}のインスタンスをDIコンテナに登録します。
 * @return {@link RetryTemplate}のインスタンス
 */
protected RetryTemplate retryTemplate() {
    RetryTemplate template = new RetryTemplate();
    template.setBackOffPolicy(backOffPolicy());
    template.setRetryPolicy(simpleRetryPolicy());
    return template;
}
 
Example 15
Source File: WebserviceDocumentItemProcessor.java    From CogStack-Pipeline with Apache License 2.0 5 votes vote down vote up
private RetryTemplate getRetryTemplate(){
    TimeoutRetryPolicy retryPolicy = new TimeoutRetryPolicy();
    retryPolicy.setTimeout(retryTimeoutMs);
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(retryBackoffMs);

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);
    return template;
}
 
Example 16
Source File: RetryExampleApplication.java    From blog-examples with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryTemplate retryTemplate() {
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(5);

    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(1500); // 1.5 seconds

    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);

    return template;
}
 
Example 17
Source File: EternalRetryTemplateConfiguration.java    From eventeum with Apache License 2.0 5 votes vote down vote up
@Bean
public RetryTemplate eternalRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();

    FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
    fixedBackOffPolicy.setBackOffPeriod(DEFAULT_BACKOFF_TIME);
    retryTemplate.setBackOffPolicy(fixedBackOffPolicy);

    AlwaysRetryPolicy retryPolicy = new AlwaysRetryPolicy();
    retryTemplate.setRetryPolicy(retryPolicy);

    return retryTemplate;
}
 
Example 18
Source File: RabbitAutoConfiguration.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private RetryTemplate createRetryTemplate(RabbitProperties.Retry properties) {
    RetryTemplate template = new RetryTemplate();
    SimpleRetryPolicy policy = new SimpleRetryPolicy();
    policy.setMaxAttempts(properties.getMaxAttempts());
    template.setRetryPolicy(policy);
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(properties.getInitialInterval());
    backOffPolicy.setMultiplier(properties.getMultiplier());
    backOffPolicy.setMaxInterval(properties.getMaxInterval());
    template.setBackOffPolicy(backOffPolicy);
    return template;
}
 
Example 19
Source File: ClickingStepDefinitions.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
/**
 * Clicks a link on the page
 *
 * @param alias       If this word is found in the step, it means the linkContent is found from the data
 *                    set.
 * @param linkContent The text content of the link we are clicking
 * @param timesAlias  If this word is found in the step, it means the times is found from the
 *                    data set.
 * @param times       If this text is set, the click operation will be repeated the specified number of times.
 * @param exists      If this text is set, an error that would be thrown because the element was not found
 *                    is ignored. Essentially setting this text makes this an optional statement.
 */
@When("^I click (?:a|an|the) link with the text content of( alias)? \"([^\"]*)\"(?:( alias)? \"(.*?)\" times)?( if it exists)?$")
public void clickLinkStep(
	final String alias,
	final String linkContent,
	final String timesAlias,
	final String times,
	final String exists) {

	try {
		final Integer fixedTimes = countConverter.convertCountToInteger(timesAlias, times);

		final String text = autoAliasUtils.getValue(
			linkContent, StringUtils.isNotBlank(alias), State.getFeatureStateForThread());

		checkState(text != null, "the aliased link content does not exist");

		final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();

		for (int i = 0; i < fixedTimes; ++i) {
			final WebElement element = browserInteropUtils.getLinkByText(webDriver, text);

			mouseMovementUtils.mouseGlide(
				webDriver,
				(JavascriptExecutor) webDriver,
				element,
				Constants.MOUSE_MOVE_TIME,
				Constants.MOUSE_MOVE_STEPS);

			final RetryTemplate template = new RetryTemplate();
			final SimpleRetryPolicy policy = new SimpleRetryPolicy();
			policy.setMaxAttempts(Constants.WEBDRIVER_ACTION_RETRIES);
			template.setRetryPolicy(policy);
			final FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
			template.setBackOffPolicy(fixedBackOffPolicy);
			template.execute(context -> {
				element.click();
				return null;
			});

			sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
		}
	} catch (final TimeoutException | NoSuchElementException ex) {
		if (StringUtils.isBlank(exists)) {
			throw ex;
		}
	}
}
 
Example 20
Source File: CuratorKafkaMonitor.java    From Kafdrop with Apache License 2.0 4 votes vote down vote up
public CuratorKafkaMonitor(CuratorFramework curatorFramework,
                           CuratorKafkaMonitorProperties properties,
                           ObjectMapper objectMapper) throws Exception
{
   this.curatorFramework = curatorFramework;
   this.properties = properties;
   this.objectMapper = objectMapper;

   try
   {
      kafkaVersion = new Version(properties.getKafkaVersion());
   }
   catch (Exception ex)
   {
      throw new IllegalStateException("Invalid kafka version: " + properties.getKafkaVersion(), ex);
   }

   threadPool = new ForkJoinPool(properties.getThreadPoolSize());

   FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
   backOffPolicy.setBackOffPeriod(properties.getRetry().getBackoffMillis());

   final SimpleRetryPolicy retryPolicy =
      new SimpleRetryPolicy(properties.getRetry().getMaxAttempts(),
                            ImmutableMap.of(InterruptedException.class, false,
                                            Exception.class, true));

   retryTemplate = new RetryTemplate();
   retryTemplate.setBackOffPolicy(backOffPolicy);
   retryTemplate.setRetryPolicy(retryPolicy);

   cacheInitCounter.set(4);

   brokerPathCache = new PathChildrenCache(curatorFramework, ZkUtils.BrokerIdsPath(), true);
   brokerPathCache.getListenable().addListener(new BrokerListener());
   brokerPathCache.getListenable().addListener((f, e) -> {
      if (e.getType() == PathChildrenCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Broker cache initialized");
      }
   });
   brokerPathCache.start(StartMode.POST_INITIALIZED_EVENT);

   topicConfigPathCache = new PathChildrenCache(curatorFramework, ZkUtils.TopicConfigPath(), true);
   topicConfigPathCache.getListenable().addListener((f, e) -> {
      if (e.getType() == PathChildrenCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Topic configuration cache initialized");
      }
   });
   topicConfigPathCache.start(StartMode.POST_INITIALIZED_EVENT);

   topicTreeCache = new TreeCache(curatorFramework, ZkUtils.BrokerTopicsPath());
   topicTreeCache.getListenable().addListener((client, event) -> {
      if (event.getType() == TreeCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Topic tree cache initialized");
      }
   });
   topicTreeCache.start();

   consumerTreeCache = new TreeCache(curatorFramework, ZkUtils.ConsumersPath());
   consumerTreeCache.getListenable().addListener((client, event) -> {
      if (event.getType() == TreeCacheEvent.Type.INITIALIZED)
      {
         cacheInitCounter.decrementAndGet();
         LOG.info("Consumer tree cache initialized");
      }
   });
   consumerTreeCache.start();

   controllerNodeCache = new NodeCache(curatorFramework, ZkUtils.ControllerPath());
   controllerNodeCache.getListenable().addListener(this::updateController);
   controllerNodeCache.start(true);
   updateController();
}