Construct service url string.

@param request      the request
@param response     the response
@param wsfedRequest the ws federation request
@return the service url
554802
protected String constructServiceUrl(final HttpServletRequest request, final HttpServletResponse response,
                                         final WSFederationRequest wsfedRequest) {
        try {
            val builder = new URIBuilder(wsFederationRequestConfigurationContext.getCallbackService().getId());

            builder.addParameter(WSFederationConstants.WA, wsfedRequest.getWa());
            builder.addParameter(WSFederationConstants.WREPLY, wsfedRequest.getWreply());
            builder.addParameter(WSFederationConstants.WTREALM, wsfedRequest.getWtrealm());

            if (StringUtils.isNotBlank(wsfedRequest.getWctx())) {
                builder.addParameter(WSFederationConstants.WCTX, wsfedRequest.getWctx());
            }
            if (StringUtils.isNotBlank(wsfedRequest.getWfresh())) {
                builder.addParameter(WSFederationConstants.WREFRESH, wsfedRequest.getWfresh());
            }
            if (StringUtils.isNotBlank(wsfedRequest.getWhr())) {
                builder.addParameter(WSFederationConstants.WHR, wsfedRequest.getWhr());
            }
            if (StringUtils.isNotBlank(wsfedRequest.getWreq())) {
                builder.addParameter(WSFederationConstants.WREQ, wsfedRequest.getWreq());
            }

            val url = builder.build();

            LOGGER.trace("Built service callback url [{}]", url);
            return org.jasig.cas.client.util.CommonUtils.constructServiceUrl(request, response,
                url.toString(), wsFederationRequestConfigurationContext.getCasProperties().getServer().getName(),
                CasProtocolConstants.PARAMETER_SERVICE,
                CasProtocolConstants.PARAMETER_TICKET, false);
        } catch (final Exception e) {
            throw new SamlException(e.getMessage(), e);
        }
    }
537608
public static String ipAddress(Request request) {
        String ipAddress = request.header("x-forwarded-for");
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("Proxy-Client-IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("WL-Proxy-Client-IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("X-Real-IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("HTTP_CLIENT_IP");
        }
        if (StringKit.isBlank(ipAddress) || UNKNOWN_MAGIC.equalsIgnoreCase(ipAddress)) {
            ipAddress = request.header("HTTP_X_FORWARDED_FOR");
        }
        return ipAddress;
    }
142229
protected String getAddress(HttpServletRequest request){
        String path = request.getScheme()+"://"+request.getServerName();
        //port
        if(request.getScheme().equals("http")&&request.getServerPort()!=80)
            path+=":"+request.getServerPort();
        if(request.getScheme().equals("https")&&request.getServerPort()!=443)
            path+=":"+request.getServerPort();
        path+=request.getRequestURI();
        return path;
    }
921837
private static String formatServiceType(final CouchbaseRequest request) {
        if (request instanceof BinaryRequest) {
            return ThresholdLogReporter.SERVICE_KV;
        } else if (request instanceof QueryRequest) {
            return ThresholdLogReporter.SERVICE_N1QL;
        } else if (request instanceof ViewRequest) {
            return ThresholdLogReporter.SERVICE_VIEW;
        } else if (request instanceof AnalyticsRequest) {
            return ThresholdLogReporter.SERVICE_ANALYTICS;
        } else if (request instanceof SearchRequest) {
            return ThresholdLogReporter.SERVICE_FTS;
        } else if (request instanceof ConfigRequest) {
            // Shouldn't be user visible, but just for completeness sake.
            return "config";
        } else {
            return "unknown";
        }
    }
745460
public static HttpHost getHost(HttpRequest request) {
        HttpHost httpHost = UriUtils.extractHost(request.getRequestLine().getUri());
        String scheme = httpHost.getSchemeName();
        String host = httpHost.getHostName();
        int port = httpHost.getPort();
        Header[] headers = request.getHeaders(HttpHeaders.HOST);
        if (headers != null && headers.length != 0) {
            String headerValue = headers[0].getValue();
            String[] splitted = headerValue.split(":");
            host = splitted[0];
            if (splitted.length > 1) {
                port = Integer.parseInt(splitted[1]);
            } else {
                port = -1;
            }
        }
        return new HttpHost(host, port, scheme);
    }
853030
@Override
	public void serviceRequest(final Request request) {
		// Get the expected session token
		UIContext uic = UIContextHolder.getCurrent();
		String expected = uic.getEnvironment().getSessionToken();

		// Get the session token from the request
		String got = request.getParameter(Environment.SESSION_TOKEN_VARIABLE);

		// Check tokens match (Both null if new session)
		// or processing a GET and no token
		if (Util.equals(expected, got) || (got == null && "GET".equals(request.getMethod()))) {
			// Process request
			getBackingComponent().serviceRequest(request);
		} else {  // Invalid token
			String msg;
			if (expected == null && got != null) {
				msg = "Session for token [" + got + "] is no longer valid or timed out.";
			} else {
				msg = "Wrong session token detected for servlet request. Expected token [" + expected
						+ "] but got token [" + got + "].";
			}
			LOG.error(msg);
			String message = I18nUtilities.format(uic.getLocale(),
					InternalMessages.DEFAULT_SESSION_TOKEN_ERROR);
			throw new SystemException(message);
		}

	}
493662
public static String repositoryUrl( HttpServletRequest request ) {
        String requestURL = request.getRequestURL().toString();
        int delimiterSegmentIdx = requestURL.length();
        for (String methodName : ALL_METHODS) {
            if (requestURL.indexOf(methodName) != -1) {
                delimiterSegmentIdx = requestURL.indexOf(methodName);
                break;
            }
        }
        return requestURL.substring(0, delimiterSegmentIdx);
    }
450371
protected <R> HttpRequestBase createHttpRequest(ServiceRequest<R> request) throws IOException, WssServiceException {
        HttpPost httpRequest = new HttpPost(serviceUrl);
        httpRequest.setHeader("Accept", ClientConstants.APPLICATION_JSON);

        RequestType requestType = request.type();
        List<NameValuePair> nvps = new ArrayList<>();
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_REQUEST_TYPE, requestType.toString()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_AGENT, request.agent()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_AGENT_VERSION, request.agentVersion()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_TOKEN, request.orgToken()));
        nvps.add(new BasicNameValuePair(APIConstants.USER_KEY, request.userKey()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_REQUESTER_EMAIL, request.requesterEmail()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_PRODUCT, request.product()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_PRODUCT_VERSION, request.productVersion()));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_TIME_STAMP, String.valueOf(request.timeStamp())));
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_PLUGIN_VERSION, String.valueOf(request.pluginVersion())));
        nvps.add(new BasicNameValuePair(APIConstants.AGGREGATE_MODULES, String.valueOf(request.aggregateModules())));
        nvps.add(new BasicNameValuePair(APIConstants.PRESERVE_MODULE_STRUCTURE, String.valueOf(request.preserveModuleStructure())));
        nvps.add(new BasicNameValuePair(APIConstants.AGGREGATE_PROJECT_NAME, request.aggregateProjectName()));
        nvps.add(new BasicNameValuePair(APIConstants.AGGREGATE_PROJECT_TOKEN, request.aggregateProjectToken()));
        nvps.add(new BasicNameValuePair(APIConstants.LOG_DATA, request.logData()));
        nvps.add(new BasicNameValuePair(APIConstants.SCAN_COMMENT, request.scanComment()));
        nvps.add(new BasicNameValuePair(APIConstants.PRODUCT_TOKEN, request.productToken()));

        if (request.extraProperties() != null) {
            String strExtraProperties = gson.toJson(request.extraProperties());
            nvps.add(new BasicNameValuePair(APIConstants.EXTRA_PROPERTIES, strExtraProperties));
        } else {
            nvps.add(new BasicNameValuePair(APIConstants.EXTRA_PROPERTIES, "{}"));
        }

        String jsonDiff = null;
        switch (requestType) {
            case UPDATE:
                UpdateInventoryRequest updateInventoryRequest = (UpdateInventoryRequest) request;
                nvps.add(new BasicNameValuePair(APIConstants.SCAN_SUMMARY_INFO, gson.toJson(updateInventoryRequest.getScanSummaryInfo())));
                nvps.add(new BasicNameValuePair(APIConstants.PARAM_UPDATE_TYPE, updateInventoryRequest.getUpdateType().toString()));
                jsonDiff = gson.toJson(updateInventoryRequest.getProjects());
                break;
            case CHECK_POLICIES:
                jsonDiff = gson.toJson(((CheckPoliciesRequest) request).getProjects());
                break;
            case CHECK_POLICY_COMPLIANCE:
                CheckPolicyComplianceRequest checkPolicyComplianceRequest = (CheckPolicyComplianceRequest) request;
                nvps.add(new BasicNameValuePair(APIConstants.SCAN_SUMMARY_INFO, this.gson.toJson(checkPolicyComplianceRequest.getScanSummaryInfo())));
                nvps.add(new BasicNameValuePair(APIConstants.PARAM_FORCE_CHECK_ALL_DEPENDENCIES,
                        String.valueOf(checkPolicyComplianceRequest.isForceCheckAllDependencies())));
                jsonDiff = gson.toJson(checkPolicyComplianceRequest.getProjects());
                break;
            case CHECK_VULNERABILITIES:
                jsonDiff = gson.toJson(((CheckVulnerabilitiesRequest) request).getProjects());
                break;
            case GET_DEPENDENCY_DATA:
                jsonDiff = gson.toJson(((GetDependencyDataRequest) request).getProjects());
                break;
            case SUMMARY_SCAN:
                SummaryScanRequest summaryScanRequest = (SummaryScanRequest) request;
                jsonDiff = gson.toJson(summaryScanRequest.getProjects());
                break;
            case GET_CONFIGURATION:
                jsonDiff = gson.toJson(((ConfigurationRequest) request).getProjects());
                break;
            default:
                break;
        }

        // compress json before sending
        String compressedString = ZipUtils.compressString(jsonDiff);
        nvps.add(new BasicNameValuePair(APIConstants.PARAM_DIFF, compressedString));

        httpRequest.setEntity(new UrlEncodedFormEntity(nvps, UTF_8));

        // whitesource service http request size should be below 200 MB
        String httpRequestJson = gson.toJson(httpRequest);
        //        if(httpRequestJson.getBytes().length > APIConstants.MAX_POST_SIZE) {
        //            logger.error("WhiteSource service http request size have exceeded max limit " + APIConstants.MAX_POST_SIZE + " bytes");
        //            throw new WssServiceException("WhiteSource service http request size have exceeded max limit " + APIConstants.MAX_POST_SIZE + " bytes");
        //        }

        return httpRequest;
    }
949804
private String getRequestPath(HttpServletRequest request) {
		String url = request.getServletPath();

		if (request.getPathInfo() != null) {
			url += request.getPathInfo();
		}

		return url;
	}
907155
@Override
	public void serviceRequest(final Request request) {
		// Get window id off the request
		windowId = request.getParameter(WWindow.WWINDOW_REQUEST_PARAM_KEY);

		if (windowId == null) {
			super.serviceRequest(request);
		} else {
			// Get the window component
			ComponentWithContext target = WebUtilities.getComponentById(windowId, true);
			if (target == null) {
				throw new SystemException("No window component for id " + windowId);
			}

			// Setup the Environment on the context
			UIContext uic = UIContextHolder.getCurrentPrimaryUIContext();
			Environment originalEnvironment = uic.getEnvironment();
			uic.setEnvironment(new EnvironmentDelegate(originalEnvironment, windowId, target));

			if (attachWindow) {
				attachUI(target.getComponent());
			}
			UIContextHolder.pushContext(target.getContext());
			try {
				super.serviceRequest(request);
			} finally {
				uic.setEnvironment(originalEnvironment);
				UIContextHolder.popContext();
			}
		}
	}
279944
public static String getBaseUrl(HttpServletRequest request){
        String baseUrl = null;					
		String host = request.getHeader(WebConstants.HEADER_FORWARDED_HOST);
		String prefix = request.getHeader(WebConstants.HEADER_FORWARDED_PRIFIX);
		if(StringUtils.isAnyBlank(host,prefix)){
			String[] segs = StringUtils.split(request.getRequestURL().toString(),"/");
			baseUrl = segs[0] + "//" + segs[1];
		}else{
			//由于nginx 没有设置  proxy_set_header   X-Forwarded-Proto $scheme;
		    //导致https通过nginx转发后，在api网关获取到的scheme为：http,
			//String proto = request.getHeader(BaseConstants.HEADER_FORWARDED_ORIGN_PROTO);
			//if(proto == null)proto = request.getHeader(BaseConstants.HEADER_FORWARDED_PROTO);
			 String port = request.getHeader(WebConstants.HEADER_FORWARDED_PORT);
			String schame = "443".equals(port) ? "https://" : "http://";
			baseUrl = schame + host + prefix;
		}
		
		if(StringUtils.isNotBlank(request.getContextPath())){
			baseUrl = baseUrl + request.getContextPath();
		}
		
		return baseUrl;
	}
197642
public static String getForwardURI(HttpServletRequest request) {
        String result = (String) request.getAttribute(WebUtils.FORWARD_REQUEST_URI_ATTRIBUTE);
        if (GrailsStringUtils.isBlank(result)) result = request.getRequestURI();
        return result;
    }
877872
@Override
	public void serviceRequest(final Request request) {

		// Get expected step count
		UIContext uic = UIContextHolder.getCurrent();
		int expected = uic.getEnvironment().getStep();

		// Get step count from the request
		int got = StepCountUtil.getRequestStep(request);

		// Match (first time, both are zero)
		// or no Step count and processing a GET
		if (expected == got || (!StepCountUtil.isStepOnRequest(request) && "GET".equals(request.
				getMethod()))) {
			// Process Service Request
			getBackingComponent().serviceRequest(request);
		} else { // Invalid step
			LOG.warn(
					"SERVER: Wrong step detected. Expected step " + expected + " but got step " + got);

			// Redirect to error page
			if (StepCountUtil.isErrorRedirect()) {
				String url = StepCountUtil.getErrorUrl();
				LOG.warn("User will be redirected to an error page. URL: " + url);
				try {
					getResponse().sendRedirect(url);
				} catch (IOException e) {
					LOG.warn("Error trying to redirect for wrong step indicator.");
				}

				// Make sure the render phase is not processed
				throw new ActionEscape();
			} else {  // Warp to the future
				// Call handle step error
				WComponent application = getUI();
				if (application instanceof WApplication) {
					LOG.warn("The handleStepError method will be called on WApplication.");
					((WApplication) application).handleStepError();
				}

				LOG.warn("The render phase will warp the user back to the future.");
			}
		}
	}
1019164
public Response makeRequest(final Request request) {

        HttpMethod method = request.getMethod();
        RequestBuilder builder = RequestBuilder.create(method.toString())
            .setUri(request.constructURL().toString())
            .setVersion(HttpVersion.HTTP_1_1)
            .setCharset(StandardCharsets.UTF_8);

        if (request.requiresAuthentication()) {
            builder.addHeader(HttpHeaders.AUTHORIZATION, request.getAuthString());
        }

        if (method == HttpMethod.POST) {
            builder.addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded");

            for (Map.Entry<String, List<String>> entry : request.getPostParams().entrySet()) {
                for (String value : entry.getValue()) {
                    builder.addParameter(entry.getKey(), value);
                }
            }
        }

        HttpResponse response = null;

        try {
            response = client.execute(builder.build());
            HttpEntity entity = response.getEntity();
            return new Response(
                // Consume the entire HTTP response before returning the stream
                entity == null ? null : new BufferedHttpEntity(entity).getContent(),
                response.getStatusLine().getStatusCode()
            );
        } catch (IOException e) {
            throw new ApiException(e.getMessage(), e);
        } finally {

            // Ensure this response is properly closed
            HttpClientUtils.closeQuietly(response);

        }

    }
99962
public static String getInServiceURL(HttpServletRequest request, String path) {
        String contextPath = ((Request) request).getContext().getContextPath();
        int port = request.getServerPort();

        return getInServiceURL(port, contextPath, path);
    }
92635
public static  String getRootDomain(HttpServletRequest request) {
		String host = request.getHeader(WebConstants.HEADER_FORWARDED_HOST);
		if(StringUtils.isBlank(host))host = request.getServerName();
		
		if(IpUtils.isIp(host) || IpUtils.LOCAL_HOST.equals(host)){
			return host;
		}
		
		String[] segs = StringUtils.split(host, POINT);
		int len = segs.length;
		return segs[len - 2] + POINT+ segs[len - 1];
	}
390326
public static ClientHttpRequest createWmsRequest(
            final MfClientHttpRequestFactory httpRequestFactory, final URI uri,
            final HttpMethod method) throws IOException {
        switch (method) {
            case GET:
                return httpRequestFactory.createRequest(uri, method);
            case POST:
                final String params = uri.getQuery();
                final URI paramlessUri;
                try {
                    paramlessUri = new URI(uri.getScheme(), uri.getUserInfo(), uri.getHost(),
                                           uri.getPort(), uri.getPath(), null, null);
                } catch (URISyntaxException e) {
                    throw new RuntimeException(e);
                }
                final ClientHttpRequest request = httpRequestFactory.createRequest(paramlessUri, method);
                final byte[] encodedParams = params.getBytes(StandardCharsets.UTF_8);
                request.getHeaders().set("Content-Type", "application/x-www-form-urlencoded");
                request.getHeaders().set("Charset", "utf-8");
                request.getHeaders().set("Content-Length", Integer.toString(encodedParams.length));
                request.getBody().write(encodedParams);
                return request;
            default:
                throw new RuntimeException("Unsupported WMS request method: " + method);
        }
    }