/*this is required to fix proxy authentication retry failure
caused by org.apache.http.client.NonRepeatableRequestException: Cannot retry request with a non-repeatable request entity
180698
protected byte[] convertInputStreamToByteArray(InputStream in) throws IOException {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        int c = -1;
        while ((c = in.read()) != -1) {
            outputStream.write(c);
        }
        outputStream.flush();
        in.close();
        return outputStream.toByteArray();
    }
746927
public static void retry(final CouchbaseRequest request, final EventSink<ResponseEvent> responseBuffer) {
        if(!responseBuffer.tryPublishEvent(ResponseHandler.RESPONSE_TRANSLATOR, request, request.observable())) {
            request.observable().onError(CouchbaseCore.BACKPRESSURE_EXCEPTION);
        }
    }
314637
function retryOrError(){ 
					if (bRetrying)
						throw Error("unit hash verification failed, unit: "+unit+", objUnit: "+JSON.stringify(objUnit));
					console.log("unit hash verification failed, will retry");
					return setTimeout(function(){
						readJointDirectly(conn, unit, callbacks, true);
					}, 60*1000);
				}
834988
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;
		String username = request.getParameter(USERNAME);
		String password = request.getParameter(PASSWORD);
		String appid = SecurityUtils.getAppidFromAuthRequest(request);

		if (requestURI.endsWith(LDAP_ACTION) && !StringUtils.isBlank(username) && !StringUtils.isBlank(password)) {
			try	{
				App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
				Authentication auth = new LDAPAuthentication(username, password).withApp(app);
				// set authentication in context to avoid warning message from SpringSecurityAuthenticationSource
				SecurityContextHolder.getContext().setAuthentication(new AnonymousAuthenticationToken("key",
						"anonymous", AuthorityUtils.createAuthorityList("ROLE_ANONYMOUS")));
				Authentication ldapAuth = getAuthenticationManager().authenticate(auth);
				if (ldapAuth != null) {
					//success!
					userAuth = getOrCreateUser(app, ldapAuth);
				}
			} catch (Exception ex) {
				LOG.info("Failed to authenticate '{}' with LDAP server: {}", username, ex.getMessage());
				throw new AuthenticationServiceException(ex.getMessage(), ex.getCause());
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
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;
    }
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();
    }
  }
1325203
def retry_using_http_NTLM_auth(self, auth_header_field, auth_header,
                                   response, auth_type, args):
        # Get the certificate of the server if using HTTPS for CBT
        server_certificate_hash = _get_server_cert(response)

        """"""
        if auth_header in response.request.headers:
            return response

        content_length = int(
            response.request.headers.get('Content-Length', '0'), base=10)
        if hasattr(response.request.body, 'seek'):
            if content_length > 0:
                response.request.body.seek(-content_length, 1)
            else:
                response.request.body.seek(0, 0)

        # Consume content and release the original connection
        # to allow our new request to reuse the same one.
        response.content
        response.raw.release_conn()
        request = response.request.copy()

        # ntlm returns the headers as a base64 encoded bytestring. Convert to
        # a string.
        context = ntlm.Ntlm()
        negotiate_message = context.create_negotiate_message(self.domain).decode('ascii')
        auth = u'%s %s' % (auth_type, negotiate_message)
        request.headers[auth_header] = auth

        # A streaming response breaks authentication.
        # This can be fixed by not streaming this request, which is safe
        # because the returned response3 will still have stream=True set if
        # specified in args. In addition, we expect this request to give us a
        # challenge and not the real content, so the content will be short
        # anyway.
        args_nostream = dict(args, stream=False)
        response2 = response.connection.send(request, **args_nostream)

        # needed to make NTLM auth compatible with requests-2.3.0

        # Consume content and release the original connection
        # to allow our new request to reuse the same one.
        response2.content
        response2.raw.release_conn()
        request = response2.request.copy()

        # this is important for some web applications that store
        # authentication-related info in cookies (it took a long time to
        # figure out)
        if response2.headers.get('set-cookie'):
            request.headers['Cookie'] = response2.headers.get('set-cookie')

        # get the challenge
        auth_header_value = response2.headers[auth_header_field]

        auth_strip = auth_type + ' '

        ntlm_header_value = next(
            s for s in (val.lstrip() for val in auth_header_value.split(','))
            if s.startswith(auth_strip)
        ).strip()

        # Parse the challenge in the ntlm context
        context.parse_challenge_message(ntlm_header_value[len(auth_strip):])

        # build response
        # Get the response based on the challenge message
        authenticate_message = context.create_authenticate_message(
            self.username,
            self.password,
            self.domain,
            server_certificate_hash=server_certificate_hash
        )
        authenticate_message = authenticate_message.decode('ascii')
        auth = u'%s %s' % (auth_type, authenticate_message)
        request.headers[auth_header] = auth

        response3 = response2.connection.send(request, **args)

        # Update the history.
        response3.history.append(response)
        response3.history.append(response2)

        # Get the session_security object created by ntlm-auth for signing and sealing of messages
        self.session_security = context.session_security

        return response3
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;
    }
81943
protected void processRequest( HttpServletRequest request,
                                   HttpServletResponse response ) throws ServletException, IOException {
        String authHeader = ((HttpServletRequest)request).getHeader("Authorization");
        String pathInfo= request.getPathInfo();
        
        Object marker = request.getSession().getAttribute("login-required-marker");
        
        if (marker == null && pathInfo.equals("login.do")) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.addHeader("WWW-Authenticate", "Basic realm =\"Realm\"");
            request.getSession().setAttribute("login-required-marker", Boolean.FALSE);
            return;
        }

        if (pathInfo.equals("login.do")) {
            response.sendRedirect(request.getContextPath() + "/Console.html");
            return;
        }
        
        String url = request.getRequestURI();
        String servletPath = request.getServletPath();

        request.getSession(true).setAttribute("initial.uri", url);
        logger.debug("Store requested uri " + url);
        
        String dest = url.substring(0, url.indexOf(servletPath));
        response.sendRedirect(dest);
    }
379965
public void onAuthenticationFailure(BoxAuthenticationInfo infoOriginal, Exception ex) {
        String msg = "failure:";
        if (getAuthStorage() != null) {
            msg += "auth storage :" + getAuthStorage().toString();
        }
        BoxAuthenticationInfo info = BoxAuthenticationInfo.unmodifiableObject(infoOriginal);
        if (info != null) {
            msg += info.getUser() == null ? "null user" : info.getUser().getId() == null ?  "null user id" : info.getUser().getId().length();
        }

        BoxLogUtils.nonFatalE("BoxAuthfail", msg , ex);
        Set<AuthListener> listeners = getListeners();
        for (AuthListener listener : listeners) {
            listener.onAuthFailure(info, ex);
        }
    }
576873
@Override
  public final HandlerEntityRequest<RS>
    lazyGetHandlerEntityRequest() throws Exception {
    String beanName = this.factoryAppBeans.getHandlerEntityRequestName();
    @SuppressWarnings("unchecked")
    HandlerEntityRequest<RS> hndlEntityReq = (HandlerEntityRequest<RS>)
      this.factoryAppBeans.getBeansMap().get(beanName);
    if (hndlEntityReq == null) {
      hndlEntityReq = new HandlerEntityRequest<RS>();
      hndlEntityReq.setWriteTi(this.factoryAppBeans.getWriteTi());
      hndlEntityReq.setReadTi(this.factoryAppBeans.getReadTi());
      hndlEntityReq.setWriteReTi(this.factoryAppBeans.getWriteReTi());
      hndlEntityReq.setWrReSpTr(this.factoryAppBeans.getWrReSpTr());
      hndlEntityReq
        .setSrvDatabase(this.factoryAppBeans.lazyGetSrvDatabase());
      hndlEntityReq.setFillEntityFromReq(
        this.factoryAppBeans.lazyGetFillEntityFromReq());
      hndlEntityReq.setLogger(
        this.factoryAppBeans.lazyGetLogger());
      hndlEntityReq.setSecureLogger(
        this.factoryAppBeans.lazyGetSecureLogger());
      hndlEntityReq
        .setEntitiesFactoriesFatory(lazyGetFctBcFctSimpleEntities());
      hndlEntityReq
        .setProcessorsFactory(lazyGetFctBnProcessors());
      hndlEntityReq
        .setProcessorsNamesHolder(new HldProcessorNames());
      hndlEntityReq
        .setEntitiesProcessorsFactory(lazyGetFctBnEntitiesProcessors());
      hndlEntityReq
        .setEntitiesProcessorsNamesHolder(new HldEntitiesProcessorNames());
      @SuppressWarnings("unchecked")
      HashMap<String, Class<?>> mcl = (HashMap<String, Class<?>>)
        this.factoryAppBeans.getEntitiesMap().clone();
      hndlEntityReq.setEntitiesMap(mcl);
      lazyGetFctBnProcessors().getSrvEntitiesPage()
        .setEntitiesMap(mcl);
      this.factoryAppBeans.getBeansMap().put(beanName, hndlEntityReq);
      this.factoryAppBeans.lazyGetLogger().info(null, AFactoryAppBeans.class,
        beanName + " has been created.");
    }
    return hndlEntityReq;
  }
1312124
BoxRevokeAuthRequest revokeOAuth(String token, String clientId, String clientSecret) {
        BoxRevokeAuthRequest request = new BoxRevokeAuthRequest(mSession, getTokenRevokeUrl(), token, clientId, clientSecret);
        request.setRequestHandler(new BoxRequest.BoxRequestHandler(request){

            @Override
            public boolean onException(BoxRequest request, BoxHttpResponse response, BoxException ex) throws BoxException.RefreshFailure {
                // if a revoke request fails for any reason we do not want to retry it again after the user refreshes or logs in again.
                return false;
            }
        });
        return request;
    }
1343005
@Override
    protected RpcResponse onFailure(ServiceRequestContext ctx, RpcRequest req, @Nullable Throwable cause)
            throws Exception {
        return RpcResponse.ofFailure(HttpStatusException.of(HttpStatus.SERVICE_UNAVAILABLE));
    }
1188466
@Retryable(maxAttemptsExpression = "${application.retry.max-attempts}",
        backoff = @Backoff(delayExpression = "${application.retry.delay}",
            multiplierExpression = "${application.retry.multiplier}"))
    public void consumeEvent(ConsumerRecord<String, String> message) {
        MdcUtils.putRid();
        try {
            log.info("Consume event from topic [{}]", message.topic());
            try {
                ConfigEvent event = mapper.readValue(message.value(), ConfigEvent.class);

                log.info("Process event from topic [{}], event_id ='{}'",
                    message.topic(), event.getEventId());
                configService.updateConfigurations(event.getCommit(), event.getPaths());
            } catch (IOException e) {
                log.error("Config topic message has incorrect format: '{}'", message.value(), e);
            }
        } finally {
            MdcUtils.removeRid();
        }
    }
1019791
def request(self, method, url, proxies=None, **kwargs):
        
        if not self._tried_get_pac:
            self.get_pac()

        # Whether we obtained or are trying to obtain a proxy from the PAC.
        # PAC is not in use if this request has proxies provided as a parameter, or if the session has disabled PAC.
        using_pac = proxies is None and self._proxy_resolver and self.pac_enabled

        if using_pac:
            proxies = self._proxy_resolver.get_proxy_for_requests(url)

        while True:
            proxy_url = list(proxies.values())[0] if proxies else None
            try:
                response = super(PACSession, self).request(method, url, proxies=proxies, **kwargs)
            except Exception as request_exc:
                # Use PAC's proxy failover rules if the proxy used for the request is from the PAC,
                # and this exception represents a proxy failure.
                if using_pac and proxy_url and self._exc_proxy_failure_filter(request_exc):
                    try:
                        proxies = self.do_proxy_failover(proxy_url, url)
                        continue
                    except ProxyConfigExhaustedError:
                        # No failover option, not even DIRECT. Bubble up original exception.
                        self._proxy_resolver.unban_all()
                raise request_exc  # In PY2, just saying 'raise' may re-raise ProxyConfigExhaustedError.

            # Use PAC's proxy failover rules if the proxy used for the request is from the PAC,
            # and this response represents a proxy failure.
            if using_pac and proxy_url and self._response_proxy_failure_filter(response):
                try:
                    proxies = self.do_proxy_failover(proxy_url, url)
                    continue
                except ProxyConfigExhaustedError:
                    # No failover option, not even DIRECT. Return response as-is.
                    self._proxy_resolver.unban_all()
                    return response

            return response
1196938
@Override
	public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response)
			throws IOException {
		final String requestURI = request.getRequestURI();
		UserAuthentication userAuth = null;

		if (requestURI.endsWith(TWITTER_ACTION)) {
			String verifier = request.getParameter("oauth_verifier");
			String appid = SecurityUtils.getAppidFromAuthRequest(request);
			String denied = request.getParameter("denied");
			String redirectURI = SecurityUtils.getRedirectUrl(request) + (appid == null ? "" : "?appid=" + appid);
			App app = Para.getDAO().read(App.id(appid == null ? Config.getRootAppIdentifier() : appid));
			String[] keys = SecurityUtils.getOAuthKeysForApp(app, Config.TWITTER_PREFIX);
			if (denied != null) {
				throw new BadCredentialsException("Cancelled.");
			}

			if (verifier == null && stepOne(response, redirectURI, keys)) {
				return null;
			} else {
				userAuth = stepTwo(request, verifier, keys, app);
			}
		}

		return SecurityUtils.checkIfActive(userAuth, SecurityUtils.getAuthenticatedUser(userAuth), true);
	}
1096226
private void retryInit() throws GeomajasException {
		// do not hammer the service
		long now = System.currentTimeMillis();
		if (now > lastInitRetry + cooldownTimeBetweenInitializationRetries) {
			lastInitRetry = now;
			try {
				log.debug("Retrying to (re-)initialize layer {}", getId());
				postConstruct();
			} catch (Exception e) { // NOSONAR
				log.warn("Failed initializing layer: ", e.getMessage());
			}
		}
		if (!usable) {
			throw new GeomajasException(ExceptionCode.LAYER_CONFIGURATION_PROBLEM);
		}
	}