Method to get the retry handler which is used to retry to establish the HTTP connection

@return returns the IntuitRetryPolicyHandler
@throws com.intuit.ipp.exception.FMSException the FMSException
966210
private IntuitRetryPolicyHandler getRetryHandler() throws FMSException {
        IntuitRetryPolicyHandler handler = null;
        String policy = Config.getProperty(Config.RETRY_MODE);
        if (policy.equalsIgnoreCase("fixed")) {
            String retryCountStr = Config.getProperty(Config.RETRY_FIXED_COUNT);
            String retryIntervalStr = Config.getProperty(Config.RETRY_FIXED_INTERVAL);
            try {
                handler = new IntuitRetryPolicyHandler(Integer.parseInt(retryCountStr),
                        Integer.parseInt(retryIntervalStr));
            } catch (NumberFormatException e) {
                throw new ConfigurationException(e);
            }

        } else if (policy.equalsIgnoreCase("incremental")) {
            String retryCountStr = Config.getProperty(Config.RETRY_INCREMENTAL_COUNT);
            String retryIntervalStr = Config.getProperty(Config.RETRY_INCREMENTAL_INTERVAL);
            String retryIncrementStr = Config.getProperty(Config.RETRY_INCREMENTAL_INCREMENT);
            try {
                handler = new IntuitRetryPolicyHandler(Integer.parseInt(retryCountStr),
                        Integer.parseInt(retryIntervalStr), Integer.parseInt(retryIncrementStr));
            } catch (NumberFormatException e) {
                throw new ConfigurationException(e);
            }

        } else if (policy.equalsIgnoreCase("exponential")) {
            String retryCountStr = Config.getProperty(Config.RETRY_EXPONENTIAL_COUNT);
            String minBackoffStr = Config.getProperty(Config.RETRY_EXPONENTIAL_MIN_BACKOFF);
            String maxBackoffStr = Config.getProperty(Config.RETRY_EXPONENTIAL_MAX_BACKOFF);
            String deltaBackoffStr = Config.getProperty(Config.RETRY_EXPONENTIAL_DELTA_BACKOFF);

            try {
                handler = new IntuitRetryPolicyHandler(Integer.parseInt(retryCountStr),
                        Integer.parseInt(minBackoffStr), Integer.parseInt(maxBackoffStr),
                        Integer.parseInt(deltaBackoffStr));
            } catch (NumberFormatException e) {
                throw new ConfigurationException(e);
            }
        }

        return handler;
    }
313522
public JKExceptionHandlerInfo getHandler(final Class<? extends Throwable> clas) {
		final JKExceptionHandler handler = this.handlers.get(clas);
		if (handler != null) {
			final JKExceptionHandlerInfo info = new JKExceptionHandlerInfo();
			info.setExceptionClass(clas).setHandler(handler);
			return info;
		}
		return null;
	}
74101
private RetryPolicy getDefaultRetryPolicy() {
        return RetryPolicyBuilder.standard()
                .retryOnExceptions(ConnectException.class, BindException.class, ConnectTimeoutException.class)
                .retryOnStatusCodes(429)
                .backoffStrategy(PredefinedRetryPolicies.DEFAULT_BACKOFF_STRATEGY_V2)
                .maxNumberOfRetries(PredefinedRetryPolicies.DEFAULT_MAX_ERROR_RETRY)
                .build();
    }
509760
private com.datastax.driver.core.policies.RetryPolicy getCustomRetryPolicy(Properties props)

    {
        String customRetryPolicy = (String) props.get(CUSTOM_RETRY_POLICY);
        Class<?> clazz = null;
        Method getter = null;
        try
        {
            clazz = Class.forName(customRetryPolicy);
            com.datastax.driver.core.policies.RetryPolicy retryPolicy = (com.datastax.driver.core.policies.RetryPolicy) KunderaCoreUtils
                    .createNewInstance(clazz);
            if (retryPolicy != null)
            {
                return retryPolicy;
            }
            getter = clazz.getDeclaredMethod(GET_INSTANCE);
            return (com.datastax.driver.core.policies.RetryPolicy) getter.invoke(null, (Object[]) null);
        }
        catch (ClassNotFoundException e)
        {
            logger.error(e.getMessage());
            throw new KunderaException("Please make sure class " + customRetryPolicy
                    + " set in property file exists in classpath " + e.getMessage());
        }
        catch (IllegalAccessException e)
        {
            logger.error(e.getMessage());
            throw new KunderaException("Method " + getter.getName() + " must be declared public " + e.getMessage());
        }
        catch (NoSuchMethodException e)
        {
            logger.error(e.getMessage());
            throw new KunderaException("Please make sure getter method of " + clazz.getSimpleName()
                    + " is named \"getInstance()\"");
        }
        catch (InvocationTargetException e)
        {
            logger.error(e.getMessage());
            throw new KunderaException("Error while executing \"getInstance()\" method of Class "
                    + clazz.getSimpleName() + ": " + e.getMessage());
        }
    }
155856
ManagementRequestHandler<Void, Void> getCloseHandler() {
        return new AbstractAttachmentHandler() {
            @Override
            void handleRequest(TimedStreamEntry entry, FlushableDataOutput output) throws IOException {
                // no-op as AbstractAttachmentHandler will close the entry after calling this
            }

            @Override
            void handleMissingStream(int requestId, int index, FlushableDataOutput output) throws IOException {
                // no-op as there's nothing to do
            }
        };
    }
529674
public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
		LOG.debug("In retry request");
		if (exception == null) {
			throw new IllegalArgumentException("Exception parameter may not be null");
		} else  if (context == null) {
			throw new IllegalArgumentException("HTTP context may not be null");
		}

		if (executionCount > this.retryCount) {
			return checkPolicy(executionCount);
		} else if (exception instanceof NoHttpResponseException) {
			// Retry if the server dropped connection on us
			return checkPolicy(executionCount);
		} else if (exception instanceof InterruptedIOException) {
			// Timeout
			return false;
		} else if (exception instanceof UnknownHostException) {
			// Unknown host
			return false;
		} else if (exception instanceof ConnectException) {
			// Connection refused
			return false;
		} else if (exception instanceof SSLException) {
			// SSL handshake exception
			return false;
		} else if (exception instanceof ProtocolException) {
			// protocol exception
			return false;
		} else if (exception instanceof SaslException) {
			// Sasl exception
			return false;
		}

		HttpRequest request = (HttpRequest) context.getAttribute(HttpCoreContext.HTTP_REQUEST);
		boolean idempotent = !(request instanceof HttpEntityEnclosingRequest);
		if (idempotent) {
			// Retry if the request is considered idempotent
			return checkPolicy(executionCount);
		}

		Boolean b = (Boolean) context.getAttribute(HttpCoreContext.HTTP_REQ_SENT);
		boolean sent = (b != null && b.booleanValue());

		// if (!sent || this.requestSentRetryEnabled) {
		// Retry if the request has not been sent fully or
		// if it's OK to retry methods that have been sent
		if (!sent) {
			return checkPolicy(executionCount);
		}
		// otherwise do not retry
		return false;
	}
128237
protected TranWrapper getCurrentTranWrapper() throws ResourceException {

        final boolean isTracingEnabled = TraceComponent.isAnyTracingEnabled();

        if (isTracingEnabled && tc.isEntryEnabled()) {
            Tr.entry(this, tc, "getCurrentTranWrapper");
        }

        // If the MCWrapper has not been completely initialized and we are working with an RA
        // that supports deferred enlistment of transactions, then let's re-initialize for the
        // UOW which we are already involved with.
        // This was a special fix that was put in for JMS Managed Sessions, but it
        // could apply to other internal connection types that might require this support.
        if ((state == STATE_ACTIVE_INUSE) && (gConfigProps.isDynamicEnlistmentSupported())) {
            if (isTracingEnabled && tc.isDebugEnabled()) {
                Tr.debug(this, tc, "State is STATE_ACTIVE_INUSE, calling initializeForUOW()...");
            }
            cm.initializeForUOW(this, true); // second parm indicates source of call is deferred enlistment.
        }

        if ((state != STATE_TRAN_WRAPPER_INUSE) && (state != STATE_ACTIVE_INUSE)) {
            IllegalStateException e = new IllegalStateException("getCurrentTranWrapper: illegal state exception. State = " + getStateString() + " MCW = "
                                                                + mcWrapperObject_hexString);
            Object[] parms = new Object[] { "getCurrentTranWrapper", e };
            Tr.error(tc, "ILLEGAL_STATE_EXCEPTION_J2CA0079", parms);
            throw e;
        }

        TranWrapper tranWrapper = null;
        switch (tranWrapperInUse) {
            case XATXWRAPPER:
                tranWrapper = xaTranWrapper;
                break;
            case LOCALTXWRAPPER:
                tranWrapper = localTranWrapper;
                break;
            case NOTXWRAPPER:
                tranWrapper = noTranWrapper;
                break;
            case RRSGLOBALTXWRAPPER:
                tranWrapper = rrsGlobalTranWrapper;
                break;
            case RRSLOCALTXWRAPPER:
                tranWrapper = rrsLocalTranWrapper;
                break;
            default:
                // Need RAS and Trace here.
                IllegalStateException e = new IllegalStateException("getCurrentTranWrapper: illegal transaction state exception. State = "
                                                                    + getTranWrapperString());
                Object[] parms = new Object[] { "getCurrentTranWrapper", e };
                Tr.error(tc, "ILLEGAL_STATE_EXCEPTION_J2CA0079", parms);
                throw e;
        }

        if (isTracingEnabled && tc.isEntryEnabled()) {
            Tr.exit(this, tc, "getCurrentTranWrapper", getTranWrapperString());
        }

        return tranWrapper;
    }
1171783
public final void retry(final ConnectionState state, final RetryHandler retryHandler, final ConnectionFailHandler failHandler) throws RetryCancelled {
    if (state.retryCount == 0) {
      state.msBeforeRetry = this.startRetryTime;
    }

    state.retryCount++;
    state.uriIndex = state.retryCount % state.uris.length;

    if (this.shouldRetry(state)) {
      if (logger.isDebugEnabled()) {
        logger.debug("Retry {} to send command", state.retryCount);
      }

      if(state.msBeforeRetry > 0) {
        try {
          state.loop.schedule(new Runnable() {
            @Override
            public void run() {
              try {
                retryHandler.doRetry(state);
              } catch (IOException e) {
                failHandler.catchException(e);
              }
            }
          }, state.msBeforeRetry, TimeUnit.MILLISECONDS);
        } catch (IllegalStateException e) {
          failHandler.catchException(
            new IOException(new CancellationException("Etcd client was closed"))
          );
        }
      } else {
        try {
          retryHandler.doRetry(state);
        } catch (IOException e) {
          failHandler.catchException(e);
        }
      }
    } else {
      throw new RetryCancelled();
    }
  }
1237962
private IAsyncHandler<Throwable> createPolicyErrorHandler() {
        return error -> resultHandler.handle(AsyncResultImpl.<IEngineResult> create(error));
    }
441110
@Override
    @FFDCIgnore({ RESTHandlerInternalError.class, RESTHandlerUserError.class, RESTHandlerMethodNotAllowedError.class, RESTHandlerUnsupportedMediaType.class,
                 RESTHandlerJsonException.class })
    public boolean handleRequest(RESTRequest request, RESTResponse response) throws IOException {
        final String requestURL = request.getContextPath() + request.getPath();
        final HandlerInfo handlerInfo = getHandler(requestURL);
        final boolean isRouting = DefaultRoutingHelper.containsLegacyRoutingContext(request) || DefaultRoutingHelper.containsRoutingContext(request);

        if (handlerInfo == null && !isRouting) {
            //calling proxy servlet will handle this case 
            return false;
        }

        try {
            //Security checks applicable to /ibm/api participants
            if (request.getContextPath().equals(RESTHandler.PROPERTY_REST_HANDLER_DEFAULT_CONTEXT_ROOT)) {
                //Check if the handler is doing custom security or not.
                //The first argument will be true if we're routing the call and a corresponding service wasn't present on this controller
                if (handlerInfo == null || !hasProperty(handlerInfo.handlerRef, RESTHandler.PROPERTY_REST_HANDLER_CUSTOM_SECURITY)) {
                    //This path is not performing custom security, so check for default authorization
                    if (!getAuthorizationHelper().checkAdministratorRole(request, response)) {
                        //We failed the check, so return true, since the default authorization helper would have filled up the response already.
                        return true;
                    }
                }
            }

            //If we matched a path that had variables, extended the request to contain the resolved variables
            if (handlerInfo != null && handlerInfo.path != null && handlerInfo.path.containsVariable()) {
                //When mapping variables we don't include the context root
                request = new ExtendedRESTRequestImpl(request, handlerInfo.path.mapVariables(requestURL));
            }

            //Routing special code
            if (isRouting) {
                //Check if we're doing custom routing or not
                if (handlerInfo == null || !hasProperty(handlerInfo.handlerRef, RESTHandler.PROPERTY_REST_HANDLER_CUSTOM_ROUTING)) {
                    //This path is not doing custom routing, so use the routing helper
                    getRoutingHelper().routeRequest(request, response);
                    return true;
                }
                //...there's routing context, but matched handler wants to do custom routing, so let the request go through
            }

            try {
                //Delegate request to handler
                handlerInfo.handler.handleRequest(request, response);
            } catch (RESTHandlerInternalError ie) {
                //Handlers general internal errors and osgi errors
                response.sendError(ie.getStatusCode(), ie.getMessage());
            } catch (RESTHandlerUserError ue) {
                response.sendError(ue.getStatusCode(), ue.getMessage());
            } catch (RESTHandlerUnsupportedMediaType e) {
                response.sendError(e.getStatusCode(), e.getMessage());
            } catch (RESTHandlerMethodNotAllowedError e) {
                //A 405 response (Method Not Allowed) needs to have the response header of "Allow", to say which methods can be used
                response.setResponseHeader("Allow", e.getAllowedMethods());
                response.sendError(e.getStatusCode());
            } catch (RESTHandlerJsonException e) {
                if (e.isMessageContentJSON()) {
                    response.setStatus(e.getStatusCode());
                    response.setContentType("application/json");
                    response.setCharacterEncoding("UTF-8");
                    response.getWriter().write(e.getMessage());
                } else {
                    response.sendError(e.getStatusCode(), e.getMessage());
                }
            }

        } catch (IOException ioe) {
            response.sendError(500, ioe.getMessage());
        }

        return true;
    }
1289197
public URLStreamHandler getHandler() throws Exception {
        String handlerString = getSSLProtocolPackageHandler() + ".https.Handler";
        URLStreamHandler streamHandler = null;

        try {
            ClassLoader cl = AccessController.doPrivileged(getCtxClassLoader);
            if (cl != null) {
                streamHandler = (URLStreamHandler) cl.loadClass(handlerString).newInstance();
            } else {
                streamHandler = (URLStreamHandler) Class.forName(handlerString).newInstance();
            }
            return streamHandler;
        } catch (Exception e) {
            FFDCFilter.processException(e, getClass().getName(), "getHandler", this);
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled())
                Tr.debug(tc, "Exception loading https stream handler.", new Object[] { e });
            Tr.error(tc, "ssl.load.https.stream.handler.CWPKI0025E", new Object[] { handlerString, e.getMessage() });
            throw e;
        }
    }
338909
public RetryPolicy<R> onRetriesExceeded(CheckedConsumer<? extends ExecutionCompletedEvent<R>> listener) {
    retriesExceededListener = EventListener.of(Assert.notNull(listener, "listener"));
    return this;
  }
610911
private IAsyncResultHandler<IEngineResult> wrapResultHandler(final IAsyncResultHandler<IEngineResult> handler) {
        return (IAsyncResult<IEngineResult> result) -> {
            boolean doRecord = true;
            if (result.isError()) {
                recordErrorMetrics(result.getError());
            } else {
                IEngineResult engineResult = result.getResult();
                if (engineResult.isFailure()) {
                    recordFailureMetrics(engineResult.getPolicyFailure());
                } else {
                    recordSuccessMetrics(engineResult.getApiResponse());
                    doRecord = false; // don't record the metric now because we need to record # of bytes downloaded, which hasn't happened yet
                }
            }
            requestMetric.setRequestEnd(new Date());
            if (doRecord) {
                metrics.record(requestMetric);
            }
            handler.handle(result);
        };
    }
364727
protected int getRetryInterval() throws ActivityException {
        try {
            String v = getAttributeValueSmart(PROP_RETRY_INTERVAL);
            return StringHelper.getInteger(v, 600);
        }
        catch (PropertyException ex) {
            throw new ActivityException(ex.getMessage(), ex);
        }
    }
917323
private static <E extends Throwable> E wrapIfNecessary(Throwable throwable)
			throws RetryException {
		if (throwable instanceof Error) {
			throw (Error) throwable;
		}
		else if (throwable instanceof Exception) {
			@SuppressWarnings("unchecked")
			E rethrow = (E) throwable;
			return rethrow;
		}
		else {
			throw new RetryException("Exception in retry", throwable);
		}
	}
453456
public HTTPRequest retry(final int maxRetries, final Retryable retryable, final WaitStrategy waitStrategy) {
        if (maxRetries <= 0) {
            throw new IllegalArgumentException("maxRetries must be > 0");
        }
        if (retryable == null) {
            throw new IllegalArgumentException("retryable must not be null");
        }
        if (waitStrategy == null) {
            throw new IllegalArgumentException("waitStrategy must not be null");
        }
        this.maxRetries = maxRetries;
        this.retryable = retryable;
        this.waitStrategy = waitStrategy;
        return this;
    }
880809
public ExceptionHandlerImpl getHandler(Class<? extends Exception> exceptionClass) {
        // If the exception map does not contain the provided exception class, it might
        // still be that a superclass of the exception class is.
        if (!this.exceptionMap.containsKey(exceptionClass)) {

            Class<?> superclass = exceptionClass.getSuperclass();
            do {
                // Is the superclass mapped?
                if (this.exceptionMap.containsKey(superclass)) {
                    // Use the handler for the mapped superclass, and cache handler
                    // for this exception class
                    ExceptionHandlerImpl handler = this.exceptionMap.get(superclass);
                    this.exceptionMap.put(exceptionClass, handler);
                    return handler;
                }

                // Iteratively walk through the exception class's superclasses
                superclass = superclass.getSuperclass();
            } while (superclass != null);

            // No handler found either for the superclasses of the exception class
            // We cache the null value to prevent future
            this.exceptionMap.put(exceptionClass, null);
            return null;
        }

        // Direct map
        return this.exceptionMap.get(exceptionClass);
    }