org.springframework.retry.support.RetryTemplate

Here are the examples of the java api org.springframework.retry.support.RetryTemplate taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

84 Examples 7

19 Source : CMSClient.java
with Apache License 2.0
from oneops

public void setRetryTemplate(RetryTemplate retryTemplate) {
    this.retryTemplate = retryTemplate;
}

19 Source : HttpBlockchainEventBroadcaster.java
with Apache License 2.0
from eventeum

/**
 * A BlockchainEventBroadcaster that broadcasts the events via a http post.
 *
 * The url to post to for block and contract events can be configured via the
 * broadcast.http.contractEvents and broadcast.http.blockEvents properties.
 *
 * @author Craig Williams <[email protected]>
 */
public clreplaced HttpBlockchainEventBroadcaster implements BlockchainEventBroadcaster {

    private HttpBroadcasterSettings settings;

    private RestTemplate restTemplate;

    private RetryTemplate retryTemplate;

    public HttpBlockchainEventBroadcaster(HttpBroadcasterSettings settings, RetryTemplate retryTemplate) {
        this.settings = settings;
        restTemplate = new RestTemplate();
        this.retryTemplate = retryTemplate;
    }

    @Override
    public void broadcastNewBlock(BlockDetails block) {
        retryTemplate.execute((context) -> {
            final ResponseEnreplacedy<Void> response = restTemplate.postForEnreplacedy(settings.getBlockEventsUrl(), block, Void.clreplaced);
            checkForSuccessResponse(response);
            return null;
        });
    }

    @Override
    public void broadcastContractEvent(ContractEventDetails eventDetails) {
        retryTemplate.execute((context) -> {
            final ResponseEnreplacedy<Void> response = restTemplate.postForEnreplacedy(settings.getContractEventsUrl(), eventDetails, Void.clreplaced);
            checkForSuccessResponse(response);
            return null;
        });
    }

    @Override
    public void broadcastTransaction(TransactionDetails transactionDetails) {
    }

    private void checkForSuccessResponse(ResponseEnreplacedy<Void> response) {
        if (response.getStatusCode() != HttpStatus.OK) {
            throw new BroadcastException(String.format("Received a %s response when broadcasting via http", response.getStatusCode()));
        }
    }
}

19 Source : RetryHandler.java
with BSD 3-Clause "New" or "Revised" License
from all-of-us

public abstract clreplaced RetryHandler<E extends Exception> {

    private final RetryTemplate retryTemplate;

    private static RetryTemplate retryTemplate(BackOffPolicy backOffPolicy, RetryPolicy retryPolicy) {
        RetryTemplate retryTemplate = new RetryTemplate();
        retryTemplate.setBackOffPolicy(backOffPolicy);
        retryTemplate.setRetryPolicy(retryPolicy);
        retryTemplate.setThrowLastExceptionOnExhausted(true);
        return retryTemplate;
    }

    public RetryHandler(BackOffPolicy backOffPolicy, RetryPolicy retryPolicy) {
        this(retryTemplate(backOffPolicy, retryPolicy));
    }

    public RetryHandler(RetryTemplate retryTemplate) {
        this.retryTemplate = retryTemplate;
    }

    @SuppressWarnings("unchecked")
    public final <T> T run(RetryCallback<T, E> retryCallback) {
        try {
            return retryTemplate.execute(retryCallback);
        } catch (RetryException retryException) {
            throw new ServerErrorException(retryException.getCause());
        } catch (Exception exception) {
            throw convertException((E) exception);
        }
    }

    public final <T> T runAndThrowChecked(RetryCallback<T, E> retryCallback) throws E {
        return retryTemplate.execute(retryCallback);
    }

    protected abstract WorkbenchException convertException(E exception);
}

19 Source : RetryConfig.java
with Apache License 2.0
from adorsys

@Bean
public RetryOperations retryOperations(FlowableProperties flowableProperties) {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(flowableProperties.getNumberOfRetries()));
    return retryTemplate;
}

18 Source : SpringRetryCircuitBreaker.java
with Apache License 2.0
from spring-cloud

/**
 * @author Ryan Baxter
 */
public clreplaced SpringRetryCircuitBreaker implements CircuitBreaker {

    private String id;

    private SpringRetryConfigBuilder.SpringRetryConfig config;

    private Optional<Customizer<RetryTemplate>> retryTemplateCustomizer;

    private RetryTemplate retryTemplate;

    public SpringRetryCircuitBreaker(String id, SpringRetryConfigBuilder.SpringRetryConfig config, Optional<Customizer<RetryTemplate>> retryTemplateCustomizer) {
        this.id = id;
        this.config = config;
        this.retryTemplateCustomizer = retryTemplateCustomizer;
        this.retryTemplate = new RetryTemplate();
    }

    @Override
    public <T> T run(Supplier<T> toRun, Function<Throwable, T> fallback) {
        retryTemplate.setBackOffPolicy(config.getBackOffPolicy());
        retryTemplate.setRetryPolicy(config.getRetryPolicy());
        retryTemplateCustomizer.ifPresent(customizer -> customizer.customize(retryTemplate));
        return retryTemplate.execute(context -> toRun.get(), context -> fallback.apply(context.getLastThrowable()), new DefaultRetryState(id, config.isForceRefreshState(), config.getStateClreplacedifier()));
    }
}

18 Source : PubSubBlockSubscriptionStrategy.java
with Apache License 2.0
from eventeum

public clreplaced PubSubBlockSubscriptionStrategy extends AbstractBlockSubscriptionStrategy<NewHead> {

    private static final String PUB_SUB_EXECUTOR_NAME = "PUBSUB";

    private RetryTemplate retryTemplate;

    private AsyncTaskService asyncService;

    public PubSubBlockSubscriptionStrategy(Web3j web3j, String nodeName, AsyncTaskService asyncService, BlockNumberService blockNumberService) {
        super(web3j, nodeName, asyncService, blockNumberService);
        this.asyncService = asyncService;
    }

    @Override
    public Disposable subscribe() {
        final BigInteger startBlock = getStartBlock();
        final DefaultBlockParameter blockParam = DefaultBlockParameter.valueOf(startBlock);
        // New heads can only start from latest block so we need to obtain missing blocks first
        blockSubscription = web3j.replayPastBlocksFlowable(blockParam, true).doOnComplete(() -> blockSubscription = subscribeToNewHeads()).subscribe(ethBlock -> triggerListeners(convertToEventeumBlock(ethBlock)));
        return blockSubscription;
    }

    private Disposable subscribeToNewHeads() {
        final Disposable disposable = web3j.newHeadsNotifications().subscribe(newHead -> {
            // Need to execute this is a seperate thread to workaround websocket thread deadlock
            asyncService.execute(ExecutorNameFactory.build(PUB_SUB_EXECUTOR_NAME, nodeName), () -> triggerListeners(newHead.getParams().getResult()));
        });
        if (disposable.isDisposed()) {
            throw new BlockchainException("Error when subscribing to newheads.  Disposable already disposed.");
        }
        return disposable;
    }

    NewHead convertToNewHead(EthBlock ethBlock) {
        final BasicNewHead newHead = new BasicNewHead();
        newHead.setHash(ethBlock.getBlock().getHash());
        newHead.setNumber(ethBlock.getBlock().getNumberRaw());
        newHead.setTimestamp(ethBlock.getBlock().getTimestampRaw());
        return newHead;
    }

    @Override
    Block convertToEventeumBlock(NewHead blockObject) {
        return new Web3jBlock(getEthBlock(blockObject.getHash()).getBlock(), nodeName);
    }

    Block convertToEventeumBlock(EthBlock blockObject) {
        return new Web3jBlock(blockObject.getBlock(), nodeName);
    }

    protected RetryTemplate getRetryTemplate() {
        if (retryTemplate == null) {
            retryTemplate = new RetryTemplate();
            final FixedBackOffPolicy fixedBackOffPolicy = new FixedBackOffPolicy();
            fixedBackOffPolicy.setBackOffPeriod(500);
            retryTemplate.setBackOffPolicy(fixedBackOffPolicy);
            final SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
            retryPolicy.setMaxAttempts(10);
            retryTemplate.setRetryPolicy(retryPolicy);
        }
        return retryTemplate;
    }

    private EthBlock getEthBlock(String blockHash) {
        return getRetryTemplate().execute((context) -> {
            try {
                final EthBlock block = web3j.ethGetBlockByHash(blockHash, true).send();
                if (block == null || block.getBlock() == null) {
                    throw new BlockchainException(String.format("Block not found. Hash: %s", blockHash));
                }
                return block;
            } catch (IOException e) {
                throw new BlockchainException("Unable to retrieve block details", e);
            }
        });
    }

    @Setter
    private clreplaced BasicNewHead extends NewHead {

        private String hash;

        private String number;

        private String timestamp;

        @Override
        public String getHash() {
            return hash;
        }

        @Override
        public String getNumber() {
            return number;
        }

        @Override
        public String getTimestamp() {
            return timestamp;
        }
    }
}

17 Source : KafkaConsumerConfiguration.java
with Apache License 2.0
from sflpro

private RetryTemplate retryTemplate() {
    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy());
    template.setBackOffPolicy(backOffPolicy());
    return template;
}

17 Source : CircuitBreakerRetryTemplateTests.java
with Eclipse Public License 1.0
from rhwayfun

/**
 * Created by ZhongCB on 2017/9/8.
 */
public clreplaced CircuitBreakerRetryTemplateTests {

    private static final String RECOVERED = "RECOVERED";

    private static final String RESULT = "RESULT";

    private RetryTemplate retryTemplate;

    private RecoveryCallback<Object> recovery;

    private MockRetryCallback callback;

    private DefaultRetryState state;

    @Before
    public void init() {
        this.callback = new MockRetryCallback();
        this.recovery = new RecoveryCallback<Object>() {

            @Override
            public Object recover(RetryContext context) throws Exception {
                return RECOVERED;
            }
        };
        this.retryTemplate = new RetryTemplate();
        this.callback.setAttemptsBeforeSuccess(1);
        // No rollback by default (so exceptions are not rethrown)
        this.state = new DefaultRetryState("retry", new BinaryExceptionClreplacedifier(false));
    }

    @Test
    public void testCircuitOpenWhenNotRetryable() throws Throwable {
        this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy()));
        Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        replacedertEquals(1, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
        result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        // circuit is now open so no more attempts
        replacedertEquals(1, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
    }

    @Test
    public void testCircuitOpenWithNoRecovery() throws Throwable {
        this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new NeverRetryPolicy()));
        this.retryTemplate.setThrowLastExceptionOnExhausted(true);
        try {
            this.retryTemplate.execute(this.callback, this.state);
        } catch (Exception e) {
            replacedertEquals(this.callback.exceptionToThrow, e);
            replacedertEquals(1, this.callback.getAttempts());
        }
        try {
            this.retryTemplate.execute(this.callback, this.state);
        } catch (Exception e) {
            replacedertEquals(this.callback.exceptionToThrow, e);
            // circuit is now open so no more attempts
            replacedertEquals(1, this.callback.getAttempts());
        }
    }

    @Test
    public void testCircuitOpensWhenDelegateNotRetryable() throws Throwable {
        this.retryTemplate.setRetryPolicy(new CircuitBreakerRetryPolicy(new SimpleRetryPolicy()));
        this.callback.setAttemptsBeforeSuccess(10);
        Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        replacedertEquals(1, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
        replacedertFalse(this.callback.status.isOpen());
        result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        // circuit is now open so no more attempts
        replacedertEquals(3, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
        replacedertTrue(this.callback.status.isOpen());
    }

    @Test
    public void testWindowResetsAfterTimeout() throws Throwable {
        CircuitBreakerRetryPolicy retryPolicy = new CircuitBreakerRetryPolicy(new SimpleRetryPolicy());
        this.retryTemplate.setRetryPolicy(retryPolicy);
        retryPolicy.setOpenTimeout(100);
        this.callback.setAttemptsBeforeSuccess(10);
        Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        replacedertEquals(1, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
        replacedertFalse(this.callback.status.isOpen());
        Thread.sleep(200L);
        result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        // circuit is reset after sleep window
        replacedertEquals(2, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
        replacedertFalse(this.callback.status.isOpen());
    }

    @Test
    public void testCircuitClosesAfterTimeout() throws Throwable {
        CircuitBreakerRetryPolicy retryPolicy = new CircuitBreakerRetryPolicy(new NeverRetryPolicy());
        this.retryTemplate.setRetryPolicy(retryPolicy);
        retryPolicy.setResetTimeout(100);
        Object result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        replacedertEquals(1, this.callback.getAttempts());
        replacedertEquals(RECOVERED, result);
        replacedertTrue(this.callback.status.isOpen());
        // Sleep longer than the timeout
        Thread.sleep(200L);
        replacedertFalse(this.callback.status.isOpen());
        result = this.retryTemplate.execute(this.callback, this.recovery, this.state);
        // circuit closed again now
        replacedertEquals(RESULT, result);
    }

    protected static clreplaced MockRetryCallback implements RetryCallback<Object, Exception> {

        private int attemptsBeforeSuccess;

        private Exception exceptionToThrow = new Exception();

        private CircuitBreakerRetryPolicy.CircuitBreakerRetryContext status;

        @Override
        public Object doWithRetry(RetryContext status) throws Exception {
            this.status = (CircuitBreakerRetryPolicy.CircuitBreakerRetryContext) status;
            int attempts = getAttempts();
            attempts++;
            status.setAttribute("attempts", attempts);
            if (attempts <= this.attemptsBeforeSuccess) {
                throw this.exceptionToThrow;
            }
            return RESULT;
        }

        public int getAttempts() {
            if (!this.status.hasAttribute("attempts")) {
                this.status.setAttribute("attempts", 0);
            }
            int attempts = (Integer) this.status.getAttribute("attempts");
            return attempts;
        }

        public void setAttemptsBeforeSuccess(int attemptsBeforeSuccess) {
            this.attemptsBeforeSuccess = attemptsBeforeSuccess;
        }

        public void setExceptionToThrow(Exception exceptionToThrow) {
            this.exceptionToThrow = exceptionToThrow;
        }
    }
}

17 Source : BlockchainEventBroadcasterConfiguration.java
with Apache License 2.0
from eventeum

@Bean
@ConditionalOnMissingBean
@ConditionalOnProperty(name = BROADCASTER_PROPERTY, havingValue = "HTTP")
public BlockchainEventBroadcaster httpBlockchainEventBroadcaster(HttpBroadcasterSettings settings, @Qualifier("eternalRetryTemplate") RetryTemplate retryTemplate) {
    final BlockchainEventBroadcaster broadcaster = new HttpBlockchainEventBroadcaster(settings, retryTemplate);
    return onlyOnceWrap(broadcaster);
}

17 Source : MetadataSyncJob.java
with BSD 3-Clause "New" or "Revised" License
from dhis2

/**
 * This is the runnable that takes care of the Metadata Synchronization.
 * Leverages Spring RetryTemplate to exhibit retries. The retries are
 * configurable through the dhis.conf.
 *
 * @author anilkumk
 * @author David Katuscak <[email protected]>
 */
@Slf4j
@Component("metadataSyncJob")
public clreplaced MetadataSyncJob extends SynchronizationJob {

    public static final String VERSION_KEY = "version";

    public static final String DATA_PUSH_SUMMARY = "dataPushSummary";

    public static final String EVENT_PUSH_SUMMARY = "eventPushSummary";

    public static final String TRACKER_PUSH_SUMMARY = "trackerPushSummary";

    public static final String GET_METADATAVERSION = "getMetadataVersion";

    public static final String GET_METADATAVERSIONSLIST = "getMetadataVersionsList";

    public static final String METADATA_SYNC = "metadataSync";

    public static final String METADATA_SYNC_REPORT = "metadataSyncReport";

    public static final String[] keys = { DATA_PUSH_SUMMARY, EVENT_PUSH_SUMMARY, GET_METADATAVERSION, GET_METADATAVERSIONSLIST, METADATA_SYNC, VERSION_KEY };

    private final SystemSettingManager systemSettingManager;

    private final RetryTemplate retryTemplate;

    private final SynchronizationManager synchronizationManager;

    private final MetadataSyncPreProcessor metadataSyncPreProcessor;

    private final MetadataSyncPostProcessor metadataSyncPostProcessor;

    private final MetadataSyncService metadataSyncService;

    private final MetadataRetryContext metadataRetryContext;

    // -------------------------------------------------------------------------
    // Implementation
    // -------------------------------------------------------------------------
    public MetadataSyncJob(SystemSettingManager systemSettingManager, RetryTemplate retryTemplate, SynchronizationManager synchronizationManager, MetadataSyncPreProcessor metadataSyncPreProcessor, MetadataSyncPostProcessor metadataSyncPostProcessor, MetadataSyncService metadataSyncService, MetadataRetryContext metadataRetryContext) {
        checkNotNull(systemSettingManager);
        checkNotNull(retryTemplate);
        checkNotNull(synchronizationManager);
        checkNotNull(metadataSyncPreProcessor);
        checkNotNull(metadataSyncPostProcessor);
        checkNotNull(metadataSyncService);
        checkNotNull(metadataRetryContext);
        this.systemSettingManager = systemSettingManager;
        this.retryTemplate = retryTemplate;
        this.synchronizationManager = synchronizationManager;
        this.metadataSyncPreProcessor = metadataSyncPreProcessor;
        this.metadataSyncPostProcessor = metadataSyncPostProcessor;
        this.metadataSyncService = metadataSyncService;
        this.metadataRetryContext = metadataRetryContext;
    }

    @Override
    public JobType getJobType() {
        return JobType.META_DATA_SYNC;
    }

    @Override
    public void execute(JobConfiguration jobConfiguration) {
        log.info("Metadata Sync cron Job started");
        try {
            MetadataSyncJobParameters jobParameters = (MetadataSyncJobParameters) jobConfiguration.getJobParameters();
            retryTemplate.execute(retryContext -> {
                metadataRetryContext.setRetryContext(retryContext);
                clearFailedVersionSettings();
                runSyncTask(metadataRetryContext, jobParameters);
                return null;
            }, retryContext -> {
                log.info("Metadata Sync failed! Sending mail to Admin");
                updateMetadataVersionFailureDetails(metadataRetryContext);
                metadataSyncPostProcessor.sendFailureMailToAdmin(metadataRetryContext);
                return null;
            });
        } catch (Exception e) {
            String customMessage = "Exception occurred while executing metadata sync task." + e.getMessage();
            log.error(customMessage, e);
        }
    }

    @Override
    public ErrorReport validate() {
        Optional<ErrorReport> errorReport = validateRemoteServerAvailability(synchronizationManager, MetadataSyncJob.clreplaced);
        return errorReport.orElse(super.validate());
    }

    synchronized void runSyncTask(MetadataRetryContext context, MetadataSyncJobParameters jobParameters) throws MetadataSyncServiceException, DhisVersionMismatchException {
        metadataSyncPreProcessor.setUp(context);
        metadataSyncPreProcessor.handleDataValuePush(context, jobParameters);
        metadataSyncPreProcessor.handleEventProgramsDataPush(context, jobParameters);
        metadataSyncPreProcessor.handleCompleteDataSetRegistrationDataPush(context);
        metadataSyncPreProcessor.handleTrackerProgramsDataPush(context, jobParameters);
        MetadataVersion metadataVersion = metadataSyncPreProcessor.handleCurrentMetadataVersion(context);
        List<MetadataVersion> metadataVersionList = metadataSyncPreProcessor.handleMetadataVersionsList(context, metadataVersion);
        if (metadataVersionList != null) {
            for (MetadataVersion dataVersion : metadataVersionList) {
                MetadataSyncParams syncParams = new MetadataSyncParams(new MetadataImportParams(), dataVersion);
                boolean isSyncRequired = metadataSyncService.isSyncRequired(syncParams);
                MetadataSyncSummary metadataSyncSummary = null;
                if (isSyncRequired) {
                    metadataSyncSummary = handleMetadataSync(context, dataVersion);
                } else {
                    metadataSyncPostProcessor.handleVersionAlreadyExists(context, dataVersion);
                    break;
                }
                boolean abortStatus = metadataSyncPostProcessor.handleSyncNotificationsAndAbortStatus(metadataSyncSummary, context, dataVersion);
                if (abortStatus) {
                    break;
                }
                clearFailedVersionSettings();
            }
        }
        log.info("Metadata sync cron job ended ");
    }

    // ----------------------------------------------------------------------------------------
    // Private Methods
    // ----------------------------------------------------------------------------------------
    private MetadataSyncSummary handleMetadataSync(MetadataRetryContext context, MetadataVersion dataVersion) throws DhisVersionMismatchException {
        MetadataSyncParams syncParams = new MetadataSyncParams(new MetadataImportParams(), dataVersion);
        MetadataSyncSummary metadataSyncSummary = null;
        try {
            metadataSyncSummary = metadataSyncService.doMetadataSync(syncParams);
        } catch (MetadataSyncServiceException e) {
            log.error("Exception happened  while trying to do metadata sync  " + e.getMessage(), e);
            context.updateRetryContext(METADATA_SYNC, e.getMessage(), dataVersion);
            throw e;
        } catch (DhisVersionMismatchException e) {
            context.updateRetryContext(METADATA_SYNC, e.getMessage(), dataVersion);
            throw e;
        }
        return metadataSyncSummary;
    }

    private void updateMetadataVersionFailureDetails(MetadataRetryContext retryContext) {
        Object version = retryContext.getRetryContext().getAttribute(VERSION_KEY);
        if (version != null) {
            MetadataVersion metadataVersion = (MetadataVersion) version;
            systemSettingManager.saveSystemSetting(SettingKey.METADATA_FAILED_VERSION, metadataVersion.getName());
            systemSettingManager.saveSystemSetting(SettingKey.METADATA_LAST_FAILED_TIME, new Date());
        }
    }

    private void clearFailedVersionSettings() {
        systemSettingManager.deleteSystemSetting(SettingKey.METADATA_FAILED_VERSION);
        systemSettingManager.deleteSystemSetting(SettingKey.METADATA_LAST_FAILED_TIME);
    }
}

17 Source : RetriableLockTest.java
with MIT License
from alturkovic

@Test
public void shouldNotRetryWhenFirstAttemptIsSuccessful() {
    when(lock.acquire(anyList(), anyString(), anyLong())).thenReturn("abc");
    final RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new NeverRetryPolicy());
    final RetriableLock retriableLock = new RetriableLock(lock, retryTemplate);
    final String token = retriableLock.acquire(Collections.singletonList("key"), "defaultStore", 1000L);
    replacedertThat(token).isEqualTo("abc");
}

17 Source : RetriableLockTest.java
with MIT License
from alturkovic

@Test
public void shouldRetryWhenFirstAttemptIsNotSuccessful() {
    when(lock.acquire(anyList(), anyString(), anyLong())).thenReturn(null).thenReturn("abc");
    final RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(2));
    final RetriableLock retriableLock = new RetriableLock(lock, retryTemplate);
    final String token = retriableLock.acquire(Collections.singletonList("key"), "defaultStore", 1000L);
    replacedertThat(token).isEqualTo("abc");
    verify(lock, times(2)).acquire(anyList(), anyString(), anyLong());
}

17 Source : RetriableLockTest.java
with MIT License
from alturkovic

@Test(expected = LockNotAvailableException.clreplaced)
public void shouldFailRetryWhenFirstAttemptIsNotSuccessful() {
    when(lock.acquire(anyList(), anyString(), anyLong())).thenReturn(null);
    final RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new NeverRetryPolicy());
    final RetriableLock retriableLock = new RetriableLock(lock, retryTemplate);
    final String token = retriableLock.acquire(Collections.singletonList("key"), "defaultStore", 1000L);
    replacedertThat(token).isEqualTo("abc");
}

17 Source : RetriableLock.java
with MIT License
from alturkovic

/**
 * A {@link Lock} wrapper for retrying {@link #acquire} method calls. This wrapper will retry the acquire method
 * only as specified by the provided {@link RetryTemplate}.
 */
@Data
public clreplaced RetriableLock implements Lock {

    private final Lock lock;

    private final RetryTemplate retryTemplate;

    @Override
    public String acquire(final List<String> keys, final String storeId, final long expiration) {
        return retryTemplate.execute(ctx -> {
            final String token = lock.acquire(keys, storeId, expiration);
            if (StringUtils.isEmpty(token)) {
                throw new LockNotAvailableException(String.format("Lock not available for keys: %s in store %s", keys, storeId));
            }
            return token;
        });
    }

    @Override
    public boolean release(final List<String> keys, final String storeId, final String token) {
        return lock.release(keys, storeId, token);
    }

    @Override
    public boolean refresh(final List<String> keys, final String storeId, final String token, final long expiration) {
        return lock.refresh(keys, storeId, token, expiration);
    }
}

16 Source : RabbitMQConfigMultipleConnection.java
with MIT License
from Tradeshift

@Bean
public RabbitTemplate rabbitTemplateTS() {
    RabbitTemplate template = new RabbitTemplate(getConnectionFactoryTS());
    template.setMessageConverter(producerJackson2MessageConverterTS());
    RetryTemplate retry = new RetryTemplate();
    retry.setBackOffPolicy(new ExponentialBackOffPolicy());
    template.setRetryTemplate(retry);
    return template;
}

16 Source : RabbitMQConfig.java
with MIT License
from Tradeshift

@Bean
public RabbitTemplate rabbitTemplate() throws IOException {
    RabbitTemplate template = new RabbitTemplate(getConnectionFactory());
    template.setMessageConverter(producerJackson2MessageConverter());
    RetryTemplate retry = new RetryTemplate();
    retry.setBackOffPolicy(new ExponentialBackOffPolicy());
    template.setRetryTemplate(retry);
    return template;
}

16 Source : ResourceReadyChecker.java
with Apache License 2.0
from shinesolutions

/**
 * Ensures external dependencies are available before starting to read messages from the queue
 * @return true if startup successful, false if not
 */
public boolean isResourcesReady() {
    boolean isStartupOk = false;
    ExponentialBackOffPolicy exponentialBackOffPolicy = getExponentialBackOffPolicy();
    SimpleRetryPolicy retryPolicy = getSimpleRetryPolicy();
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(retryPolicy);
    retryTemplate.setBackOffPolicy(exponentialBackOffPolicy);
    retryTemplate.setThrowLastExceptionOnExhausted(true);
    logger.info("Waiting for Author ELB to be in healthy state");
    try {
        isStartupOk = retryTemplate.execute(c -> {
            boolean result = aemInstanceHelperService.isAutreplacedlbHealthy();
            if (// Needs to be healthy
            !result)
                throw new Exception("Author ELB does not appear to be in a healthy state");
            return result;
        });
    } catch (Exception e) {
        logger.error("Failed to receive healthy state from Author ELB", e);
    }
    return isStartupOk;
}

16 Source : RetryExamples.java
with Eclipse Public License 1.0
from rhwayfun

private void retryExample2() throws Exception {
    RetryTemplate retryTemplate = new RetryTemplate();
    TimeoutRetryPolicy timeoutRetryPolicy = new TimeoutRetryPolicy();
    timeoutRetryPolicy.setTimeout(100);
    retryTemplate.setRetryPolicy(timeoutRetryPolicy);
    Integer result = retryTemplate.execute(new RetryCallback<Integer, Exception>() {

        int i = 0;

        @Override
        public Integer doWithRetry(RetryContext retryContext) throws Exception {
            System.out.println("retry context: " + retryContext.getParent() + ", retryCount: " + retryContext.getRetryCount() + ", attributes: " + Arrays.toString(retryContext.attributeNames()) + ", lastException: " + retryContext.getLastThrowable() + ", isExhaustedOnly: " + retryContext.isExhaustedOnly());
            return len(i++);
        }
    });
    System.out.println("final result: " + result);
}

16 Source : RetryExamples.java
with Eclipse Public License 1.0
from rhwayfun

private void retryExample8() throws Exception {
    RetryTemplate retryTemplate = new RetryTemplate();
    // 当前状态的名称,当把状态放入缓存时,通过该key查询获取
    Object key = "mykey";
    // 是否每次都重新生成上下文还是从缓存中查询,即全局模式(如熔断器策略时从缓存中查询)
    boolean isForceRefresh = true;
    // 对DataAccessException进行回滚,即如果抛出对DataAccessException不进行重试
    BinaryExceptionClreplacedifier rollbackClreplacedifier = new BinaryExceptionClreplacedifier(Collections.singleton(DataAccessException.clreplaced));
    RetryState state = new DefaultRetryState(key, isForceRefresh, rollbackClreplacedifier);
    String result = retryTemplate.execute(new RetryCallback<String, RuntimeException>() {

        @Override
        public String doWithRetry(RetryContext context) throws RuntimeException {
            System.out.println("retry count:" + context.getRetryCount());
            throw new TypeMismatchDataAccessException("");
        // throw new IllformedLocaleException("");
        }
    }, new RecoveryCallback<String>() {

        @Override
        public String recover(RetryContext context) throws Exception {
            return "default";
        }
    }, state);
    System.out.println("result: " + result);
}

16 Source : RetryExamples.java
with Eclipse Public License 1.0
from rhwayfun

private void retryExample3() throws Exception {
    RetryTemplate retryTemplate = new RetryTemplate();
    SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
    simpleRetryPolicy.setMaxAttempts(3);
    retryTemplate.setRetryPolicy(simpleRetryPolicy);
    Integer result = retryTemplate.execute(new RetryCallback<Integer, Exception>() {

        int i = 0;

        @Override
        public Integer doWithRetry(RetryContext retryContext) throws Exception {
            log.info("retry count: {}", retryContext.getRetryCount());
            return len(i++);
        }
    }, new RecoveryCallback<Integer>() {

        @Override
        public Integer recover(RetryContext retryContext) throws Exception {
            log.info("after retry: {}, recovery method called!", retryContext.getRetryCount());
            return Integer.MAX_VALUE;
        }
    });
    log.info("final result: {}", result);
}

16 Source : RetryExamples.java
with Eclipse Public License 1.0
from rhwayfun

private void retryExample7() throws Exception {
    RetryTemplate retryTemplate = new RetryTemplate();
    CompositeRetryPolicy compositeRetryPolicy = new CompositeRetryPolicy();
    SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
    simpleRetryPolicy.setMaxAttempts(3);
    TimeoutRetryPolicy timeoutRetryPolicy = new TimeoutRetryPolicy();
    timeoutRetryPolicy.setTimeout(1000L);
    // 如果重试总耗时超过1s,重试次数不超过3次,重试中止;如果总耗时未超过1s,但是重试次数超过3次,重试中止
    compositeRetryPolicy.setPolicies(new RetryPolicy[] { simpleRetryPolicy, timeoutRetryPolicy });
    retryTemplate.setRetryPolicy(compositeRetryPolicy);
    Integer result = retryTemplate.execute(new RetryCallback<Integer, Exception>() {

        int i = 0;

        @Override
        public Integer doWithRetry(RetryContext retryContext) throws Exception {
            log.info("retry count: {}", retryContext.getRetryCount());
            return len2(i++);
        }
    }, new RecoveryCallback<Integer>() {

        @Override
        public Integer recover(RetryContext context) throws Exception {
            return -1;
        }
    });
    log.info("final result: {}", result);
}

16 Source : RetryExamples.java
with Eclipse Public License 1.0
from rhwayfun

private void retryExample6() throws Exception {
    RetryTemplate retryTemplate = new RetryTemplate();
    CompositeRetryPolicy compositeRetryPolicy = new CompositeRetryPolicy();
    SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
    simpleRetryPolicy.setMaxAttempts(10000000);
    TimeoutRetryPolicy timeoutRetryPolicy = new TimeoutRetryPolicy();
    timeoutRetryPolicy.setTimeout(10L);
    // 如果重试总耗时超过1s,或重试次数超过3次,重试中止;如果总耗时未超过1s,但是重试次数超过3次,重试中止
    compositeRetryPolicy.setPolicies(new RetryPolicy[] { simpleRetryPolicy, timeoutRetryPolicy });
    retryTemplate.setRetryPolicy(compositeRetryPolicy);
    Integer result = retryTemplate.execute(new RetryCallback<Integer, Exception>() {

        int i = 0;

        @Override
        public Integer doWithRetry(RetryContext retryContext) throws Exception {
            log.info("retry count: {}", retryContext.getRetryCount());
            return len2(i++);
        }
    }, new RecoveryCallback<Integer>() {

        @Override
        public Integer recover(RetryContext context) throws Exception {
            return -1;
        }
    });
    log.info("final result: {}", result);
}

16 Source : RetryExamples.java
with Eclipse Public License 1.0
from rhwayfun

private void retryExample9() throws Exception {
    RetryTemplate template = new RetryTemplate();
    CircuitBreakerRetryPolicy retryPolicy = new CircuitBreakerRetryPolicy(new SimpleRetryPolicy(1));
    retryPolicy.setOpenTimeout(20000);
    retryPolicy.setResetTimeout(1);
    template.setRetryPolicy(retryPolicy);
    for (int i = 0; i < 10; i++) {
        // Thread.sleep(1000);
        // log.info("index: {}", i);
        try {
            Object key = "circuit";
            boolean isForceRefresh = false;
            RetryState state = new DefaultRetryState(key, isForceRefresh);
            int finalI = i;
            String result = template.execute(new RetryCallback<String, RuntimeException>() {

                @Override
                public String doWithRetry(RetryContext context) throws RuntimeException {
                    log.info("index:{}, retry count: {}", finalI, context.getRetryCount());
                    throw new RuntimeException("timeout");
                }
            }, new RecoveryCallback<String>() {

                @Override
                public String recover(RetryContext context) throws Exception {
                    return "default";
                }
            }, state);
            System.out.println(result);
        } catch (Exception e) {
            System.out.println(e);
        }
    }
}

16 Source : SimpleDemo.java
with Apache License 2.0
from houbb

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

16 Source : Application.java
with The Unlicense
from diegopacheco

@Override
public void run(String... args) throws Exception {
    service().service();
    RetryTemplate template = new RetryTemplate();
    TimeoutRetryPolicy policy = new TimeoutRetryPolicy();
    policy.setTimeout(30000L);
    template.setRetryPolicy(policy);
    String result = template.execute(new RetryCallback<String, Exception>() {

        public String doWithRetry(RetryContext context) {
            return "Works";
        }
    });
    System.out.println("works: " + result);
}

16 Source : DefaultRetryTemplateConverterTest.java
with MIT License
from alturkovic

@Test
@Locked(retry = @Interval("100"), timeout = @Interval("2000"))
public void shouldConstructCustomizedRetryTemplate() {
    final Locked locked = new Object() {
    }.getClreplaced().getEnclosingMethod().getAnnotation(Locked.clreplaced);
    final RetryTemplateConverter converter = new DefaultRetryTemplateConverter(intervalConverter);
    final RetryTemplate retryTemplate = converter.construct(locked);
    replacedertRetryTemplateConstruction(retryTemplate, 2000L, 100L);
}

16 Source : DefaultRetryTemplateConverterTest.java
with MIT License
from alturkovic

@Test
@Locked
public void shouldConstructDefaultRetryTemplate() {
    final Locked locked = new Object() {
    }.getClreplaced().getEnclosingMethod().getAnnotation(Locked.clreplaced);
    final RetryTemplateConverter converter = new DefaultRetryTemplateConverter(intervalConverter);
    final RetryTemplate retryTemplate = converter.construct(locked);
    replacedertRetryTemplateConstruction(retryTemplate, 1000L, 50L);
}

16 Source : RetryHandler.java
with BSD 3-Clause "New" or "Revised" License
from all-of-us

private static RetryTemplate retryTemplate(BackOffPolicy backOffPolicy, RetryPolicy retryPolicy) {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setBackOffPolicy(backOffPolicy);
    retryTemplate.setRetryPolicy(retryPolicy);
    retryTemplate.setThrowLastExceptionOnExhausted(true);
    return retryTemplate;
}

16 Source : DirectoryServiceImplIntegrationTest.java
with BSD 3-Clause "New" or "Revised" License
from all-of-us

private static RetryTemplate retryTemplate() {
    RetryTemplate tmpl = new RetryTemplate();
    ExponentialRandomBackOffPolicy backoff = new ExponentialRandomBackOffPolicy();
    tmpl.setBackOffPolicy(backoff);
    SimpleRetryPolicy retry = new SimpleRetryPolicy();
    retry.setMaxAttempts(10);
    tmpl.setRetryPolicy(retry);
    tmpl.setThrowLastExceptionOnExhausted(true);
    return tmpl;
}

16 Source : RocketMQInboundChannelAdapter.java
with Apache License 2.0
from alibaba

/**
 * @author <a href="mailto:[email protected]">Jim</a>
 */
public clreplaced RocketMQInboundChannelAdapter extends MessageProducerSupport {

    private static final Logger log = LoggerFactory.getLogger(RocketMQInboundChannelAdapter.clreplaced);

    private RetryTemplate retryTemplate;

    private RecoveryCallback<? extends Object> recoveryCallback;

    private RocketMQListenerBindingContainer rocketMQListenerContainer;

    private final ExtendedConsumerProperties<RocketMQConsumerProperties> consumerProperties;

    private final InstrumentationManager instrumentationManager;

    public RocketMQInboundChannelAdapter(RocketMQListenerBindingContainer rocketMQListenerContainer, ExtendedConsumerProperties<RocketMQConsumerProperties> consumerProperties, InstrumentationManager instrumentationManager) {
        this.rocketMQListenerContainer = rocketMQListenerContainer;
        this.consumerProperties = consumerProperties;
        this.instrumentationManager = instrumentationManager;
    }

    @Override
    protected void onInit() {
        if (consumerProperties == null || !consumerProperties.getExtension().getEnabled()) {
            return;
        }
        super.onInit();
        if (this.retryTemplate != null) {
            replacedert.state(getErrorChannel() == null, "Cannot have an 'errorChannel' property when a 'RetryTemplate' is " + "provided; use an 'ErrorMessageSendingRecoverer' in the 'recoveryCallback' property to " + "send an error message when retries are exhausted");
        }
        BindingRocketMQListener listener = new BindingRocketMQListener();
        rocketMQListenerContainer.setRocketMQListener(listener);
        if (retryTemplate != null) {
            this.retryTemplate.registerListener(listener);
        }
        try {
            rocketMQListenerContainer.afterPropertiesSet();
        } catch (Exception e) {
            log.error("rocketMQListenerContainer init error: " + e.getMessage(), e);
            throw new IllegalArgumentException("rocketMQListenerContainer init error: " + e.getMessage(), e);
        }
        instrumentationManager.addHealthInstrumentation(new Instrumentation(rocketMQListenerContainer.getTopic() + rocketMQListenerContainer.getConsumerGroup()));
    }

    @Override
    protected void doStart() {
        if (consumerProperties == null || !consumerProperties.getExtension().getEnabled()) {
            return;
        }
        try {
            rocketMQListenerContainer.start();
            instrumentationManager.getHealthInstrumentation(rocketMQListenerContainer.getTopic() + rocketMQListenerContainer.getConsumerGroup()).markStartedSuccessfully();
        } catch (Exception e) {
            instrumentationManager.getHealthInstrumentation(rocketMQListenerContainer.getTopic() + rocketMQListenerContainer.getConsumerGroup()).markStartFailed(e);
            log.error("RocketMQTemplate startup failed, Caused by " + e.getMessage());
            throw new MessagingException(MessageBuilder.withPayload("RocketMQTemplate startup failed, Caused by " + e.getMessage()).build(), e);
        }
    }

    @Override
    protected void doStop() {
        rocketMQListenerContainer.stop();
    }

    public void setRetryTemplate(RetryTemplate retryTemplate) {
        this.retryTemplate = retryTemplate;
    }

    public void setRecoveryCallback(RecoveryCallback<? extends Object> recoveryCallback) {
        this.recoveryCallback = recoveryCallback;
    }

    protected clreplaced BindingRocketMQListener implements RocketMQListener<Message>, RetryListener {

        @Override
        public void onMessage(Message message) {
            boolean enableRetry = RocketMQInboundChannelAdapter.this.retryTemplate != null;
            if (enableRetry) {
                RocketMQInboundChannelAdapter.this.retryTemplate.execute(context -> {
                    RocketMQInboundChannelAdapter.this.sendMessage(message);
                    return null;
                }, (RecoveryCallback<Object>) RocketMQInboundChannelAdapter.this.recoveryCallback);
            } else {
                RocketMQInboundChannelAdapter.this.sendMessage(message);
            }
        }

        @Override
        public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
            return true;
        }

        @Override
        public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        }

        @Override
        public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        }
    }
}

15 Source : RabbitMQConfigMultipleConnection.java
with MIT License
from Tradeshift

@Bean
@Primary
public RabbitTemplate rabbitTemplateDefault() {
    RabbitTemplate template = new RabbitTemplate(getConnectionFactoryDefault());
    template.setMessageConverter(producerJackson2MessageConverterDefault());
    RetryTemplate retry = new RetryTemplate();
    retry.setBackOffPolicy(new ExponentialBackOffPolicy());
    template.setRetryTemplate(retry);
    return template;
}

15 Source : CMSClient.java
with Apache License 2.0
from oneops

@Bean
protected RetryTemplate getRetryTemplate(@Value("${controller.retryCount:3}") int retryCount, @Value("${controller.intial_delay:1000}") int initialDelay, @Value("${controller.maxInterval:10000}") int maxInterval) {
    RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(new SimpleRetryPolicy(retryCount, Collections.singletonMap(RestClientException.clreplaced, true)));
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    backOffPolicy.setInitialInterval(initialDelay);
    backOffPolicy.setMaxInterval(maxInterval);
    retryTemplate.setBackOffPolicy(backOffPolicy);
    retryTemplate.setThrowLastExceptionOnExhausted(true);
    retryTemplate.registerListener(new DefaultListenerSupport());
    return retryTemplate;
}

15 Source : CamundaRequestHandler.java
with Apache License 2.0
from onap

protected RetryTemplate getRetryTemplate() {
    RetryTemplate retryTemplate = new RetryTemplate();
    Map<Clreplaced<? extends Throwable>, Boolean> retryableExceptions = new HashMap<>();
    retryableExceptions.put(ResourceAccessException.clreplaced, true);
    SimpleRetryPolicy policy = new SimpleRetryPolicy(2, retryableExceptions);
    retryTemplate.setRetryPolicy(policy);
    return retryTemplate;
}

15 Source : DefaultEventSyncService.java
with Apache License 2.0
from eventeum

@Slf4j
@Service
public clreplaced DefaultEventSyncService implements EventSyncService {

    private BlockNumberService blockNumberService;

    private EventRetriever eventRetriever;

    private EventFilterSyncStatusRepository syncStatusRepository;

    private ContractEventProcessor contractEventProcessor;

    private RetryTemplate retryTemplate;

    public DefaultEventSyncService(BlockNumberService blockNumberService, EventRetriever eventRetriever, EventFilterSyncStatusRepository syncStatusRepository, ContractEventProcessor contractEventProcessor, @Qualifier("eternalRetryTemplate") RetryTemplate retryTemplate) {
        this.blockNumberService = blockNumberService;
        this.eventRetriever = eventRetriever;
        this.syncStatusRepository = syncStatusRepository;
        this.contractEventProcessor = contractEventProcessor;
        this.retryTemplate = retryTemplate;
    }

    @Override
    public void sync(List<ContractEventFilter> filters) {
        filters.forEach(filter -> retryTemplate.execute((context) -> {
            syncFilter(filter);
            return null;
        }));
    }

    private void syncFilter(ContractEventFilter filter) {
        final Optional<EventFilterSyncStatus> syncStatus = syncStatusRepository.findById(filter.getId());
        if (!syncStatus.isPresent() || syncStatus.get().getSyncStatus() == SyncStatus.NOT_SYNCED) {
            final BigInteger startBlock = getStartBlock(filter, syncStatus);
            // Should sync to block start block number
            final BigInteger endBlock = blockNumberService.getStartBlockForNode(filter.getNode());
            log.info("Syncing event filter with id {} from block {} to {}", filter.getId(), startBlock, endBlock);
            eventRetriever.retrieveEvents(filter, startBlock, endBlock, (events) -> events.forEach(this::processEvent));
            final EventFilterSyncStatus finalSyncStatus = getEventSyncStatus(filter.getId());
            finalSyncStatus.setSyncStatus(SyncStatus.SYNCED);
            syncStatusRepository.save(finalSyncStatus);
            log.info("Event filter with id {} has completed syncing", filter.getId());
        } else {
            log.info("Event filter with id {} already synced", filter.getId());
        }
    }

    private void processEvent(ContractEventDetails contractEvent) {
        contractEventProcessor.processContractEvent(contractEvent);
        final EventFilterSyncStatus syncStatus = getEventSyncStatus(contractEvent.getFilterId());
        syncStatus.setLastBlockNumber(contractEvent.getBlockNumber());
        syncStatusRepository.save(syncStatus);
    }

    private EventFilterSyncStatus getEventSyncStatus(String id) {
        return syncStatusRepository.findById(id).orElse(EventFilterSyncStatus.builder().filterId(id).syncStatus(SyncStatus.NOT_SYNCED).build());
    }

    private BigInteger getStartBlock(ContractEventFilter contractEventFilter, Optional<EventFilterSyncStatus> syncStatus) {
        if (syncStatus.isPresent() && syncStatus.get().getLastBlockNumber().compareTo(BigInteger.ZERO) > 0) {
            return syncStatus.get().getLastBlockNumber();
        }
        return contractEventFilter.getStartBlock();
    }
}

15 Source : EternalRetryTemplateConfiguration.java
with Apache License 2.0
from eventeum

@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;
}

15 Source : MailServiceImpl.java
with Apache License 2.0
from dangdangdotcom

/**
 * Implement of {@link MailService} by spring mail starter.
 *
 * @author GeZhen
 */
@Slf4j
@Service
public clreplaced MailServiceImpl implements MailService {

    @Resource
    private JavaMailSender sender;

    @Value("${alarm.mail.from}")
    private String from;

    @Value("${alarm.mail.to}")
    private String[] adminMails;

    private RetryTemplate retryTemplate = new RetryTemplate();

    private static final int MAIL_MAX_ATTEMPTS = 3;

    private static final int MAIL_BACKOFF_PERIOD = 100;

    public MailServiceImpl() {
        SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy(MAIL_MAX_ATTEMPTS);
        retryTemplate.setRetryPolicy(retryPolicy);
        // 失败后补偿策略
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        backOffPolicy.setBackOffPeriod(MAIL_BACKOFF_PERIOD);
        retryTemplate.setBackOffPolicy(backOffPolicy);
    }

    @Override
    public void sendMail(final String replacedle, final String content, final String[] to, final String[] cc, final boolean isHtml) {
        retryTemplate.execute(retryContext -> {
            try {
                MimeMessage message = sender.createMimeMessage();
                MimeMessageHelper helper = new MimeMessageHelper(message, true, CharEncoding.UTF_8);
                helper.setFrom(from);
                helper.setTo(to);
                if (cc != null && cc.length > 0) {
                    helper.setCc(cc);
                }
                helper.setSubject(replacedle);
                helper.setText(content, isHtml);
                sender.send(message);
                return null;
            } catch (MessagingException e) {
                throw new CymbalException(e);
            }
        }, retryContext -> {
            log.error("Send mail fail", retryContext.getLastThrowable());
            throw (CymbalException) retryContext.getLastThrowable();
        });
    }

    @Override
    public void sendMailToAdmin(final String replacedle, final String content) {
        sendMail(replacedle, content, adminMails, null, false);
    }

    @Override
    public void sendHtmlMailToAdmin(final String replacedle, final String content) {
        sendMail(replacedle, content, adminMails, null, true);
    }

    @Override
    public void sendHtmlMail(final String replacedle, final String content, final String[] recivers) {
        sendMail(replacedle, content, recivers, adminMails, true);
    }
}

15 Source : WebserviceDocumentItemProcessor.java
with Apache License 2.0
from CogStack

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;
}

15 Source : AnyOrderActionService.java
with Creative Commons Zero v1.0 Universal
from CMSgov

/**
 * The main point of entry into this clreplaced.
 *
 * Call this with an item and {@link #asynchronousAction(Object)} will be called with the same item to do the action
 * asynchronously.
 *
 * @param objectToActOn The item to do an action on.
 * @return A {@link CompletableFuture} that will complete once the action completes without failure.
 */
protected CompletableFuture<S> actOnItem(T objectToActOn) {
    return CompletableFuture.supplyAsync(() -> {
        RetryTemplate retry = retryTemplate();
        API_LOG.info("Trying to execute action {}", getActionName());
        return retry.execute(context -> {
            if (context.getLastThrowable() != null) {
                API_LOG.error("Last try resulted in a thrown throwable", context.getLastThrowable());
            }
            if (context.getRetryCount() > 0) {
                API_LOG.warn("Retry {} - trying to execute action again", context.getRetryCount());
            }
            return asynchronousAction(objectToActOn);
        });
    }, taskExecutor);
}

15 Source : OMSInboundChannelAdapter.java
with Apache License 2.0
from chubaostream

/**
 * OMS Inbound Channel Adapter
 */
public clreplaced OMSInboundChannelAdapter extends MessageProducerSupport {

    private static final Log log = LogFactory.getLog(OMSInboundChannelAdapter.clreplaced);

    private RetryTemplate retryTemplate;

    private RecoveryCallback<? extends Object> recoveryCallback;

    private final OMSListenerBindingContainer omsListenerContainer;

    private final ExtendedConsumerProperties<OMSConsumerProperties> consumerProperties;

    public OMSInboundChannelAdapter(OMSListenerBindingContainer omsListenerContainer, ExtendedConsumerProperties<OMSConsumerProperties> consumerProperties) {
        this.omsListenerContainer = omsListenerContainer;
        this.consumerProperties = consumerProperties;
    }

    @Override
    protected void onInit() {
        if (consumerProperties == null || !consumerProperties.getExtension().getEnable()) {
            return;
        }
        super.onInit();
        if (this.retryTemplate != null) {
            replacedert.state(getErrorChannel() == null, "Cannot have an 'errorChannel' property when a 'RetryTemplate' is " + "provided; use an 'ErrorMessageSendingRecover' in the 'recoveryCallback' property to " + "send an error message when retries are exhausted");
        }
        BindingOMSListener listener = new BindingOMSListener();
        BindingOMSBatchListener batchListener = new BindingOMSBatchListener();
        omsListenerContainer.setMessageListener(listener);
        omsListenerContainer.setBatchMessageListener(batchListener);
        if (retryTemplate != null) {
            this.retryTemplate.registerListener(listener);
            this.retryTemplate.registerListener(batchListener);
        }
        try {
            omsListenerContainer.afterPropertiesSet();
        } catch (Exception e) {
            throw new IllegalArgumentException("omsListenerContainer init error: " + e.getMessage(), e);
        }
    }

    @Override
    protected void doStart() {
        if (consumerProperties == null || !consumerProperties.getExtension().getEnable()) {
            return;
        }
        try {
            omsListenerContainer.start();
        } catch (Exception e) {
            log.error("jmqListenerContainer startup failed, Caused by " + e.getMessage());
            throw new MessagingException(MessageBuilder.withPayload("jmqListenerContainer startup failed, Caused by " + e.getMessage()).build(), e);
        }
    }

    @Override
    protected void doStop() {
        omsListenerContainer.stop();
    }

    public RetryTemplate getRetryTemplate() {
        return retryTemplate;
    }

    public void setRetryTemplate(RetryTemplate retryTemplate) {
        this.retryTemplate = retryTemplate;
    }

    public RecoveryCallback<? extends Object> getRecoveryCallback() {
        return recoveryCallback;
    }

    public void setRecoveryCallback(RecoveryCallback<? extends Object> recoveryCallback) {
        this.recoveryCallback = recoveryCallback;
    }

    /**
     * Binding listener
     */
    protected clreplaced BindingOMSListener implements MessageListener, RetryListener {

        @Override
        public <T, E extends Throwable> boolean open(RetryContext context, RetryCallback<T, E> callback) {
            return true;
        }

        @Override
        public <T, E extends Throwable> void close(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        }

        @Override
        public <T, E extends Throwable> void onError(RetryContext context, RetryCallback<T, E> callback, Throwable throwable) {
        }

        @Override
        public void onReceived(Message message, Context context) {
            boolean enableRetry = OMSInboundChannelAdapter.this.retryTemplate != null;
            if (enableRetry) {
                OMSInboundChannelAdapter.this.retryTemplate.execute(retryContext -> {
                    OMSInboundChannelAdapter.this.sendMessage(MessageUtil.convert2SpringMessage(message));
                    return null;
                }, (RecoveryCallback<Object>) OMSInboundChannelAdapter.this.recoveryCallback);
            } else {
                OMSInboundChannelAdapter.this.sendMessage(MessageUtil.convert2SpringMessage(message));
            }
        }
    }

    /**
     * Binding batch listener
     */
    protected clreplaced BindingOMSBatchListener implements BatchMessageListener, RetryListener {

        @Override
        public void onReceived(List<Message> list, Context context) {
            boolean enableRetry = OMSInboundChannelAdapter.this.retryTemplate != null;
            if (enableRetry) {
                OMSInboundChannelAdapter.this.retryTemplate.execute(retryContext -> {
                    list.forEach(message -> {
                        OMSInboundChannelAdapter.this.sendMessage(MessageUtil.convert2SpringMessage(message));
                    });
                    return null;
                }, (RecoveryCallback<Object>) OMSInboundChannelAdapter.this.recoveryCallback);
            } else {
                list.forEach(message -> {
                    OMSInboundChannelAdapter.this.sendMessage(MessageUtil.convert2SpringMessage(message));
                });
            }
        }

        @Override
        public <T, E extends Throwable> boolean open(RetryContext retryContext, RetryCallback<T, E> retryCallback) {
            return true;
        }

        @Override
        public <T, E extends Throwable> void close(RetryContext retryContext, RetryCallback<T, E> retryCallback, Throwable throwable) {
        }

        @Override
        public <T, E extends Throwable> void onError(RetryContext retryContext, RetryCallback<T, E> retryCallback, Throwable throwable) {
        }
    }
}

15 Source : DefaultRetriableLockFactoryTest.java
with MIT License
from alturkovic

@RunWith(MockitoJUnitRunner.clreplaced)
public clreplaced DefaultRetriableLockFactoryTest {

    @Mock
    private RetryTemplateConverter retryTemplateConverter;

    @Mock
    private Lock lock;

    @Mock
    private Locked locked;

    @Mock
    private RetryTemplate retryTemplate;

    @Test
    public void shouldGenerateRetriableLock() {
        when(retryTemplateConverter.construct(eq(locked))).thenReturn(retryTemplate);
        final RetriableLockFactory factory = new DefaultRetriableLockFactory(retryTemplateConverter);
        final RetriableLock retriableLock = factory.generate(lock, locked);
        replacedertThat(retriableLock.getLock()).isEqualTo(lock);
        replacedertThat(retriableLock.getRetryTemplate()).isEqualTo(retryTemplate);
    }
}

15 Source : DefaultRetryTemplateConverter.java
with MIT License
from alturkovic

@Override
public RetryTemplate construct(final Locked locked) {
    final RetryTemplate retryTemplate = new RetryTemplate();
    retryTemplate.setRetryPolicy(resolveLockRetryPolicy(locked));
    retryTemplate.setBackOffPolicy(resolveBackOffPolicy(locked));
    return retryTemplate;
}

14 Source : RabbitAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

private void replacedertListenerRetryTemplate(AbstractRabbitListenerContainerFactory<?> rabbitListenerContainerFactory, RetryPolicy retryPolicy) {
    DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitListenerContainerFactory);
    Advice[] adviceChain = (Advice[]) dfa.getPropertyValue("adviceChain");
    replacedertThat(adviceChain).isNotNull();
    replacedertThat(adviceChain.length).isEqualTo(1);
    dfa = new DirectFieldAccessor(adviceChain[0]);
    RetryTemplate retryTemplate = (RetryTemplate) dfa.getPropertyValue("retryOperations");
    dfa = new DirectFieldAccessor(retryTemplate);
    replacedertThat(dfa.getPropertyValue("retryPolicy")).isSameAs(retryPolicy);
}

14 Source : CleanupBean.java
with Apache License 2.0
from CogStack

public RetryTemplate getRetryTemplate() {
    // TimeoutRetryPolicy retryPolicy = new TimeoutRetryPolicy();
    // retryPolicy.setTimeout(Long.valueOf(env.getProperty("shutdownTimeout")));
    AlwaysRetryPolicy retryPolicy = new AlwaysRetryPolicy();
    FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
    backOffPolicy.setBackOffPeriod(5000);
    RetryTemplate template = new RetryTemplate();
    template.setRetryPolicy(retryPolicy);
    template.setBackOffPolicy(backOffPolicy);
    return template;
}

14 Source : PDPClient.java
with Apache License 2.0
from build-security

/**
 * The PDPClient component allow making data POST request to an OPA compatible server.
 * The client has a defined retry policy and connection timeout settings.
 */
@Component
public clreplaced PDPClient {

    private RestTemplate restTemplate;

    private RetryTemplate retryTemplate;

    @Value("${pdp.port:8181}")
    private String port;

    @Value("${pdp.hostname:localhost}")
    private String host;

    @Value("${pdp.schema:http}")
    private String schema;

    @Value("${pdp.policy.path}")
    private String policyPath;

    @Value("${pdp.readTimeout.milliseconds}")
    private int readTimeout;

    @Value("${pdp.connectionTimeout.milliseconds}")
    private int connectionTimeout;

    @Value("${pdp.retry.maxAttempts}")
    private int retryMaxAttempts;

    @Value("${pdp.retry.backoff.milliseconds}")
    private int retryBackoffMilliseconds;

    @PostConstruct
    private void postConstruct() {
        this.retryTemplate = PDPClient.createRetryTemplate(this.retryMaxAttempts, this.retryBackoffMilliseconds);
        this.restTemplate = createRestTemplate(this.readTimeout, this.connectionTimeout);
    }

    public void setRestTemplate(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public void setRetryTemplate(RetryTemplate retryTemplate) {
        this.retryTemplate = retryTemplate;
    }

    public static RestTemplate createRestTemplate(int readTimeout, int connectionTimeout) {
        // RestTemplate does not use a connection pool by default, therefore we need to use HttpComponentsClientHttpRequestFactory
        HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
        requestFactory.setReadTimeout(readTimeout);
        requestFactory.setConnectTimeout(connectionTimeout);
        // RestTemplate is safe for concurrency
        return new RestTemplate(requestFactory);
    }

    public static RetryTemplate createRetryTemplate(int retryMaxAttempts, int retryBackoffMilliseconds) {
        SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy();
        // Set the max retry attempts
        simpleRetryPolicy.setMaxAttempts(retryMaxAttempts);
        FixedBackOffPolicy backOffPolicy = new FixedBackOffPolicy();
        // set fixed backoff period in ms
        backOffPolicy.setBackOffPeriod(retryBackoffMilliseconds);
        RetryTemplate template = new RetryTemplate();
        template.setRetryPolicy(new InternalServerErrorRetryPolicy(simpleRetryPolicy));
        template.setBackOffPolicy(backOffPolicy);
        return template;
    }

    private ResponseEnreplacedy<String> evaluateEx(Object request) throws Exception {
        HttpEnreplacedy<?> requestBody = new HttpEnreplacedy<>(request);
        ResponseEnreplacedy<String> responseEnreplacedyStr = restTemplate.postForEnreplacedy(getQueryUrl(), requestBody, String.clreplaced);
        return responseEnreplacedyStr;
    }

    private ResponseEnreplacedy<String> evaluate(Object request) throws Throwable {
        return retryTemplate.execute((RetryCallback<ResponseEnreplacedy<String>, Throwable>) retryContext -> {
            return evaluateEx(request);
        });
    }

    /**
     * Performs a POST request to the data endpoint of the PDP.
     * Only if an HttpServerErrorException is thrown then a retry will be attempted.
     *
     * @param input a map containing JSON serializable objects to set as input
     * @return a JsonNode response for the given input.
     * @throws org.springframework.web.client.RestClientException
     */
    public JsonNode getJsonResponse(Map<String, Object> input) throws Throwable {
        ResponseEnreplacedy<String> responseEnreplacedyStr = evaluate(input);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readTree(responseEnreplacedyStr.getBody());
    }

    /**
     * Performs a POST request to the data endpoint of the PDP.
     * Only if an HttpServerErrorException is thrown then a retry will be attempted.
     *
     * @param request an object containing JSON serializable objects to set as request
     * @return a JsonNode response for the given request.
     * @throws org.springframework.web.client.RestClientException
     */
    public JsonNode getJsonResponse(PDPRequest request) throws Throwable {
        ResponseEnreplacedy<String> responseEnreplacedyStr = evaluate(request);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readTree(responseEnreplacedyStr.getBody());
    }

    /**
     * Performs a POST request to the data endpoint of the PDP.
     * Only if an HttpServerErrorException is thrown then a retry will be attempted.
     *
     * @param input a map containing JSON serializable objects to set as input
     * @return a Map containing attributes and the Object values
     * @throws org.springframework.web.client.RestClientException
     */
    public Map<String, Object> getMappedResponse(Map<String, Object> input) throws Throwable {
        ResponseEnreplacedy<String> responseEnreplacedyStr = evaluate(input);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(responseEnreplacedyStr.getBody(), new TypeReference<Map<String, Object>>() {
        });
    }

    /**
     * Performs a POST request to the data endpoint of the PDP.
     * Only if an HttpServerErrorException is thrown then a retry will be attempted.
     *
     * @param request an object containing JSON serializable objects to set as request
     * @return a Map containing attributes and the Object values
     * @throws org.springframework.web.client.RestClientException
     */
    public Map<String, Object> getMappedResponse(PDPRequest request) throws Throwable {
        ResponseEnreplacedy<String> responseEnreplacedyStr = evaluate(request);
        ObjectMapper objectMapper = new ObjectMapper();
        return objectMapper.readValue(responseEnreplacedyStr.getBody(), new TypeReference<Map<String, Object>>() {
        });
    }

    private String getQueryUrl() {
        return this.schema + "://" + this.host + ":" + this.port + "/v1/data" + this.policyPath;
    }
}

14 Source : RetryableConfig.java
with Apache License 2.0
from adorsys

@Bean(name = TEST_RETRY_OPS)
RetryOperations retryOperations(@Value("${test.retry.max}") int maxRetries) {
    RetryTemplate withRetry = new RetryTemplate();
    withRetry.setBackOffPolicy(new ExponentialBackOffPolicy());
    SimpleRetryPolicy retryPolicy = new SimpleRetryPolicy();
    retryPolicy.setMaxAttempts(maxRetries);
    withRetry.setRetryPolicy(retryPolicy);
    withRetry.registerListener(new LogRetryListener());
    return withRetry;
}

13 Source : RabbitAutoConfigurationTests.java
with Apache License 2.0
from yuanmabiji

@Test
public void testRabbitTemplateRetryWithCustomizer() {
    this.contextRunner.withUserConfiguration(RabbitRetryTemplateCustomizerConfiguration.clreplaced).withPropertyValues("spring.rabbitmq.template.retry.enabled:true", "spring.rabbitmq.template.retry.initialInterval:2000").run((context) -> {
        RabbitTemplate rabbitTemplate = context.getBean(RabbitTemplate.clreplaced);
        DirectFieldAccessor dfa = new DirectFieldAccessor(rabbitTemplate);
        RetryTemplate retryTemplate = (RetryTemplate) dfa.getPropertyValue("retryTemplate");
        replacedertThat(retryTemplate).isNotNull();
        dfa = new DirectFieldAccessor(retryTemplate);
        replacedertThat(dfa.getPropertyValue("backOffPolicy")).isSameAs(context.getBean(RabbitRetryTemplateCustomizerConfiguration.clreplaced).backOffPolicy);
        ExponentialBackOffPolicy backOffPolicy = (ExponentialBackOffPolicy) dfa.getPropertyValue("backOffPolicy");
        replacedertThat(backOffPolicy.getInitialInterval()).isEqualTo(100);
    });
}

13 Source : RetryTemplateFactory.java
with Apache License 2.0
from yuanmabiji

public RetryTemplate createRetryTemplate(RabbitProperties.Retry properties, RabbitRetryTemplateCustomizer.Target target) {
    PropertyMapper map = PropertyMapper.get();
    RetryTemplate template = new RetryTemplate();
    SimpleRetryPolicy policy = new SimpleRetryPolicy();
    map.from(properties::getMaxAttempts).to(policy::setMaxAttempts);
    template.setRetryPolicy(policy);
    ExponentialBackOffPolicy backOffPolicy = new ExponentialBackOffPolicy();
    map.from(properties::getInitialInterval).whenNonNull().as(Duration::toMillis).to(backOffPolicy::setInitialInterval);
    map.from(properties::getMultiplier).to(backOffPolicy::setMultiplier);
    map.from(properties::getMaxInterval).whenNonNull().as(Duration::toMillis).to(backOffPolicy::setMaxInterval);
    template.setBackOffPolicy(backOffPolicy);
    if (this.customizers != null) {
        for (RabbitRetryTemplateCustomizer customizer : this.customizers) {
            customizer.customize(target, template);
        }
    }
    return template;
}

13 Source : WsCommandHandler.java
with MIT License
from valb3r

private <T extends ClientNamed, U extends BaseMessage> void doExecute(WebSocketSession session, U message, Map<String, T> handlers, BiFunction<T, U, ? extends BaseMessage> executor) {
    T handler = handlers.get(message.getClientName());
    if (null == handler) {
        log.warn("Missing handler for {}", message);
        ErrorResponse error = buildError(message, new NoClientException());
        registry.doSend(session, error);
        return;
    }
    String oldName = Thread.currentThread().getName();
    Thread.currentThread().setName(message.getClientName() + " / " + message.getId());
    RetryTemplate retryTemplate = retryTemplate(message);
    try {
        BaseMessage result = retryTemplate.execute(context -> executor.apply(handler, message));
        // result can be null if it was WS based request
        if (null != result) {
            registry.doSend(session, result);
        }
    } catch (RateTooHighException ex) {
        NewRelic.noticeError(ex);
        ErrorResponse error = buildError(message, ex);
        error.setTransient(true);
        log.error("Sending transient error message {} in response to {}", error, message.getId());
        registry.doSend(session, error);
    } catch (Exception ex) {
        NewRelic.noticeError(ex);
        ErrorResponse error = buildError(message, ex);
        log.error("Sending error message {} in response to {}", error, message.getId());
        registry.doSend(session, error);
    } finally {
        Thread.currentThread().setName(oldName);
    }
}

13 Source : WsCommandHandler.java
with MIT License
from valb3r

private <U extends BaseMessage> RetryTemplate retryTemplate(U message) {
    RetryTemplate template = new RetryTemplate();
    if (null != message.getRetryStrategy()) {
        template.setRetryPolicy(new SimpleRetryPolicy(message.getRetryStrategy().getMaxRetries()));
        ExponentialBackOffPolicy backoff = new ExponentialBackOffPolicy();
        backoff.setInitialInterval(message.getRetryStrategy().getBaseDelayMs());
        backoff.setMultiplier(message.getRetryStrategy().getBackOffMultiplier());
        template.setBackOffPolicy(backoff);
        template.registerListener(new DoRetryListener());
    } else {
        template.setRetryPolicy(new NeverRetryPolicy());
    }
    return template;
}

13 Source : NashornRequestResultAsyncTask.java
with Apache License 2.0
from suricate-io

@Component
@Scope(value = "prototype")
public clreplaced NashornRequestResultAsyncTask implements Callable<Void> {

    /**
     * Clreplaced logger
     */
    private static final Logger LOGGER = LoggerFactory.getLogger(NashornRequestResultAsyncTask.clreplaced.getName());

    /**
     * Minimum time to wait for a result from the Nashorn request
     */
    private static final int TIMEOUT = 60;

    /**
     * Maximum number of retry to update the widget
     */
    public static final int MAX_RETRY = 10;

    /**
     * Maximum backoff period to wait before retrying
     */
    private static final int MAX_BACK_OFF_PERIOD = 10000;

    /**
     * Minimum backoff period to wait before retrying
     */
    private static final int MIN_BACK_OFF_PERIOD = 1000;

    /**
     * The dashboard schedule service
     */
    @Autowired
    private DashboardScheduleService dashboardScheduleService;

    /**
     * The scheduled asynchronous task which will execute the Nashorn request executing the widget
     */
    private ScheduledFuture<NashornResponse> scheduledNashornRequestTask;

    /**
     * The Nashorn request itself
     */
    private NashornRequest nashornRequest;

    /**
     * The Nashorn requests scheduler
     */
    private NashornRequestWidgetExecutionScheduler scheduler;

    /**
     * Retry template which will perform some retries on the widget update
     */
    private RetryTemplate retryTemplate;

    /**
     * Constructor
     *
     * @param scheduledNashornRequestTask The scheduled asynchronous task which will execute the Nashorn request executing the widget
     * @param nashornRequest The Nashorn request itself
     * @param scheduler The Nashorn requests scheduler
     */
    public NashornRequestResultAsyncTask(ScheduledFuture<NashornResponse> scheduledNashornRequestTask, NashornRequest nashornRequest, NashornRequestWidgetExecutionScheduler scheduler) {
        this.scheduledNashornRequestTask = scheduledNashornRequestTask;
        this.nashornRequest = nashornRequest;
        this.scheduler = scheduler;
        this.initRetryTemplate();
    }

    /**
     * Method automatically called by the scheduler after the given delay.
     *
     * Compute a timeout duration to wait a response from the Nashorn widget execution request.
     *
     * Wait for a response from the Nashorn request task. We wait for the given amount of time.
     *
     * Update the widget from the Nashorn response and notify the Front-End. Perform some retries
     * on the widget update. If all the retries fail, then schedule a new Nashorn request execution.
     */
    @Override
    public Void call() {
        try {
            long nashornRequestExecutionTimeout = nashornRequest.getTimeout() == null || nashornRequest.getTimeout() < TIMEOUT ? TIMEOUT : nashornRequest.getTimeout();
            LOGGER.debug("Waiting for the response of the Nashorn request of the widget instance {} (until {} seconds before timeout)", nashornRequest.getProjectWidgetId(), nashornRequestExecutionTimeout);
            // Wait for a response of the Nashorn request task
            NashornResponse nashornResponse = scheduledNashornRequestTask.get(nashornRequestExecutionTimeout, TimeUnit.SECONDS);
            retryTemplate.execute(retryContext -> {
                LOGGER.debug("Update the widget instance {} (try {}/{})", nashornResponse.getProjectWidgetId(), retryContext.getRetryCount(), MAX_RETRY);
                dashboardScheduleService.processNashornRequestResponse(nashornResponse, scheduler);
                return null;
            }, context -> {
                LOGGER.error("Updating the widget instance {} failed after {} attempts", nashornRequest.getProjectWidgetId(), MAX_RETRY);
                scheduler.schedule(nashornRequest, false);
                return null;
            });
        } catch (CancellationException cancellationException) {
            LOGGER.debug("The Nashorn request ({}) has been canceled for the widget instance {}", scheduledNashornRequestTask, nashornRequest.getProjectWidgetId(), cancellationException);
        } catch (Exception exception) {
            LOGGER.error("An error has occurred in the Nashorn request result task for the widget instance {}. The Nashorn request execution will be canceled", nashornRequest.getProjectWidgetId(), exception);
            scheduledNashornRequestTask.cancel(true);
            try {
                dashboardScheduleService.updateWidgetInstanceNoNashornResponse(exception, nashornRequest.getProjectWidgetId(), nashornRequest.getProjectId());
            } catch (Exception exception1) {
                LOGGER.error("Cannot update the widget instance {} with no Nashorn response cause of database issue. Rescheduling a new Nashorn request", nashornRequest.getProjectWidgetId(), exception1);
                scheduler.schedule(nashornRequest, false);
            }
        }
        return null;
    }

    /**
     * Init the Spring retry template which will perform some retries on the widget update
     */
    private void initRetryTemplate() {
        retryTemplate = new RetryTemplate();
        UniformRandomBackOffPolicy backOffPolicy = new UniformRandomBackOffPolicy();
        backOffPolicy.setMaxBackOffPeriod(MAX_BACK_OFF_PERIOD);
        backOffPolicy.setMinBackOffPeriod(MIN_BACK_OFF_PERIOD);
        retryTemplate.setRetryPolicy(new SimpleRetryPolicy(MAX_RETRY));
        retryTemplate.setBackOffPolicy(backOffPolicy);
    }
}

See More Examples