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

The following examples show how to use org.springframework.retry.support.RetryTemplate#execute() . 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: SimpleDemo.java    From retry with Apache License 2.0 8 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
Source File: FeatureFileImporterImpl.java    From IridiumApplicationTesting with MIT License 8 votes vote down vote up
private String 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);
		return template.execute(context -> {
			FileUtils.copyURLToFile(new URL(path), copy);
			return FileUtils.readFileToString(copy, Charset.defaultCharset());
		});
	} finally {
		FileUtils.deleteQuietly(copy);
	}
}
 
Example 3
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 4
Source File: RetryInterceptor.java    From mica with GNU Lesser General Public License v3.0 6 votes vote down vote up
@Override
public Response intercept(Chain chain) throws IOException {
	Request request = chain.request();
	RetryTemplate template = createRetryTemplate(retryPolicy);
	return template.execute(context -> {
		Response response = chain.proceed(request);
		// 结果集校验
		Predicate<ResponseSpec> respPredicate = retryPolicy.getRespPredicate();
		if (respPredicate == null) {
			return response;
		}
		// copy 一份 body
		ResponseBody body = response.peekBody(Long.MAX_VALUE);
		try (HttpResponse httpResponse = new HttpResponse(response)) {
			if (respPredicate.test(httpResponse)) {
				throw new IOException("Http Retry ResponsePredicate test Failure.");
			}
		}
		return response.newBuilder().body(body).build();
	});
}
 
Example 5
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 6
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 7
Source File: JobStatusWebhookEventListener.java    From piper with Apache License 2.0 6 votes vote down vote up
private void handleEvent (PiperEvent aEvent) {
  String jobId = aEvent.getRequiredString(DSL.JOB_ID);
  Job job = jobRepository.getById(jobId);
  if(job == null) {
    logger.warn("Unknown job: {}", jobId);
    return;
  }
  List<Accessor> webhooks = job.getWebhooks();
  for(Accessor webhook : webhooks) {
    if(Events.JOB_STATUS.equals(webhook.getRequiredString(DSL.TYPE))) {
      MapObject webhookEvent = new MapObject(webhook.asMap());
      webhookEvent.put(DSL.EVENT,aEvent.asMap());
      RetryTemplate retryTemplate = createRetryTemplate(webhook);
      retryTemplate.execute((context) -> {
        if(context.getRetryCount() == 0) {
          logger.debug("Calling webhook {} -> {}",webhook.getRequiredString(DSL.URL),webhookEvent);
        }
        else {
          logger.debug("[Retry: {}] Calling webhook {} -> {}",context.getRetryCount(),webhook.getRequiredString(DSL.URL),webhookEvent);
        }
        return rest.postForObject(webhook.getRequiredString(DSL.URL), webhookEvent, String.class);
      });
    }
  }
}
 
Example 8
Source File: BrowserInteropUtilsImpl.java    From IridiumApplicationTesting with MIT License 5 votes vote down vote up
@Override
public void setWindowSize(final int width, final int height) {
	final WebDriver webDriver = State.getThreadDesiredCapabilityMap().getWebDriverForThread();

	final boolean isChrome = browserDetection.isChrome(webDriver);
	final boolean isAndroid = browserDetection.isAndroid(webDriver);
	final boolean isIPad = browserDetection.isIPad(webDriver);
	final boolean isIPhone = browserDetection.isIPhone(webDriver);

	if (!disableInterop()) {
		if (isAndroid || isIPad || isIPhone) {
			LOGGER.info("WEBAPPTESTER-INFO-0010: Detected an Android, iPhone or iPad browser. "
				+ "Setting the window size on these browsers is not supported.");
		} else if (isChrome) {
			/*
				This step will sometimes fail in Chrome, so retry a few times in the event of an error
				because it doesn't matter if we resize a few times.
				https://github.com/SeleniumHQ/selenium/issues/1853
			  */
			final RetryTemplate template = retryService.getRetryTemplate();
			template.execute(context -> {
				webDriver.manage().window().setPosition(new Point(0, 0));
				webDriver.manage().window().setSize(new Dimension(width, height));
				return null;
			});
		}
	} else {
		webDriver.manage().window().setSize(new Dimension(width, height));
	}
}
 
Example 9
Source File: CallWebserviceProcessor.java    From batchers with Apache License 2.0 5 votes vote down vote up
@Override
public TaxWebserviceCallResult process(TaxCalculation taxCalculation) throws Exception {
    LOG.info("Web service process: " + taxCalculation);

    RetryTemplate retryTemplate = retryConfig.createRetryTemplate();
    Callable<Void> callable = () -> retryTemplate.execute(doWebserviceCallWithRetryCallback(taxCalculation));

    TaxWebserviceCallResult taxWebserviceCallResult = taxPaymentWebServiceFacade.callTaxService(taxCalculation, callable);

    return taxWebserviceCallResult;
}
 
Example 10
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 11
Source File: ClickingStepDefinitions.java    From IridiumApplicationTesting with MIT License 4 votes vote down vote up
/**
 * Clicks a link that may or may not be visible 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) hidden link with the text content( alias)? of \"([^\"]*)\"(?:( alias)? \"(.*?)\" times)?( if it exists)?$")
public void clickHiddenLinkStep(
	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 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 -> {
				final WebElement element = browserInteropUtils.getLinkByText(webDriver, text);

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

				final JavascriptExecutor js = (JavascriptExecutor) webDriver;
				js.executeScript("arguments[0].click();", element);
				return null;
			});

			sleepUtils.sleep(State.getFeatureStateForThread().getDefaultSleep());
		}
	} catch (final TimeoutException | NoSuchElementException ex) {
		if (StringUtils.isBlank(exists)) {
			throw ex;
		}
	}
}