Build the actual http request
@param request The data service request
@return The http request
510052
protected com.squareup.okhttp.Request buildHttpRequest(Request request)
    {
        RequestBody requestBody = null;
        if(request.getRequestMethod().isBodyRequest())
            requestBody = RequestBody.create(JSON, serializeBody(request));

        return new com.squareup.okhttp.Request.Builder()
                .url(buildUrl(request))
                .headers(getHeaders(request))
                .method(request.getRequestMethod().name(),requestBody)
                .build();
    }
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;
    }
714841
protected String getRequestedService(final HttpServletRequest request) {
        val targetService = request.getParameter(CasProtocolConstants.PARAMETER_TARGET_SERVICE);
        val service = request.getParameter(CasProtocolConstants.PARAMETER_SERVICE);
        val serviceAttribute = request.getAttribute(CasProtocolConstants.PARAMETER_SERVICE);

        if (StringUtils.isNotBlank(targetService)) {
            return targetService;
        }
        if (StringUtils.isNotBlank(service)) {
            return service;
        }
        if (serviceAttribute != null) {
            if (serviceAttribute instanceof Service) {
                return ((Service) serviceAttribute).getId();
            }
            return serviceAttribute.toString();
        }
        return null;
    }
775549
protected Map<String,String> convertParametersTextToMap(HTTPRequest request)
    {
        //init data structure
        Map<String,String> map=new HashMap<String,String>();

        //get parameters text
        String parametersText=request.getParametersText();
        
        if(parametersText!=null)
        {
            //split to key/value pairs (key=value)
            String[] keyValuePairs=parametersText.split("&");
            
            //get amount
            int pairsAmount=keyValuePairs.length;
            
            String keyValuePair=null;
            String[] parts=null;
            String key=null;
            String value=null;
            for(int index=0;index<pairsAmount;index++)
            {
                //get next key/value pair
                keyValuePair=keyValuePairs[index];
                
                //split to key and value
                parts=keyValuePair.split("=");
                if(parts.length==2)
                {
                    //get key
                    key=parts[0];
                    if(key.length()>0)
                    {
                        //decode key
                        key=SpiUtil.urlDecode(key);

                        //get value
                        value=parts[1].trim();

                        //decode value
                        value=SpiUtil.urlDecode(value);
                        
                        //put in data structure
                        map.put(key,value);
                    }
                }
            }
        }
        
        return map;
    }
681494
private ODataRequest buildODataRequest(HttpServletRequest servletRequest) throws IOException {
        ODataRequest.Builder builder = new ODataRequest.Builder();

        builder.setMethod(ODataRequest.Method.valueOf(servletRequest.getMethod()));

        // Unfortunately, HttpServletRequest makes it difficult to get the full URI
        StringBuilder sb = getRequestURL(servletRequest);
        String queryString = servletRequest.getQueryString();
        if (!isNullOrEmpty(queryString)) {
            sb.append('?').append(queryString);
        }
        builder.setUri(sb.toString());

        // Unfortunately, HttpServletRequest has a very old-style API to iterate the headers
        Enumeration e = servletRequest.getHeaderNames();
        while (e.hasMoreElements()) {
            String name = (String) e.nextElement();
            String value = servletRequest.getHeader(name);
            builder.setHeader(name, value);
        }

        // Read the request body
        InputStream in = servletRequest.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        int count;
        byte[] buffer = new byte[BUFFER_SIZE];
        while ((count = in.read(buffer)) != -1) {
            out.write(buffer, 0, count);
        }
        builder.setBody(out.toByteArray());

        return builder.build();
    }
1108446
public String processSearchRequest(final SearchRequest request) {
    StringBuilder builder = new StringBuilder();
    builder.append("Search for ");
    if (request.getDatabaseCode() != null) {
      builder.append("code ");
      builder.append(request.getDatabaseCode());
    }
    if (request.getQuery() != null) {
      builder.append(" with query ");
      builder.append(request.getQuery());
    }
    if (request.getPageNumber() != null) {
      builder.append(" page ");
      builder.append(request.getPageNumber());
    }
    if (request.getMaxPerPage() != null) {
      builder.append(" limited to ");
      builder.append(request.getMaxPerPage());
      builder.append(" per page");
    }
    return builder.toString();
  }
822953
public Promise<HttpResponse> send(HttpRequest request) {
		SettablePromise<HttpResponse> promise = new SettablePromise<>();
		this.promise = promise;
		assert pool == null;
		(pool = client.poolReadWrite).addLastNode(this);
		poolTimestamp = eventloop.currentTimeMillis();
		HttpHeaderValue connectionHeader = CONNECTION_KEEP_ALIVE_HEADER;
		if (client.maxKeepAliveRequests != -1) {
			if (++numberOfKeepAliveRequests >= client.maxKeepAliveRequests) {
				connectionHeader = CONNECTION_CLOSE_HEADER;
			}
		}
		request.addHeader(CONNECTION, connectionHeader);
		ByteBuf buf = renderHttpMessage(request);
		if (buf != null) {
			writeBuf(buf);
		} else {
			writeHttpMessageAsChunkedStream(request);
		}
		request.recycle();
		if (!isClosed()) {
			try {
				readHttpMessage();
			} catch (ParseException e) {
				closeWithError(e);
			}
		}
		return promise;
	}
359833
public Response api(Request request) throws IOException {
    Request req = new Request();
    req.setMethod(request.getMethod());
    req.setBaseUri(this.host);
    req.setEndpoint("/" + version + "/" + request.getEndpoint());
    req.setBody(request.getBody());
    for (Map.Entry<String, String> header : this.requestHeaders.entrySet()) {
      req.addHeader(header.getKey(), header.getValue());
    }
    for (Map.Entry<String, String> queryParam : request.getQueryParams().entrySet()) {
      req.addQueryParam(queryParam.getKey(), queryParam.getValue());
    }

    return makeCall(req);
  }
1349977
public static RequestInfo getRequestInfo(HttpServletRequest request) {
      RequestInfo requestInfo = (RequestInfo) request.getAttribute(REQUEST_INFO);
      if (requestInfo == null) {
         requestInfo = new RequestInfo(request);
         request.setAttribute(REQUEST_INFO, requestInfo);
      }
      
      return requestInfo;
   }
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);

        }

    }
79805
protected HttpClientContext createHttpContext(InternalRequest request) {
        HttpClientContext context = HttpClientContext.create();
        context.setRequestConfig(this.requestConfigBuilder.setExpectContinueEnabled(request.isExpectContinueEnabled())
                .build());
        if (this.credentialsProvider != null) {
            context.setCredentialsProvider(this.credentialsProvider);
        }
        if (this.config.isProxyPreemptiveAuthenticationEnabled()) {
            AuthCache authCache = new BasicAuthCache();
            authCache.put(this.proxyHttpHost, new BasicScheme());
            context.setAuthCache(authCache);
        }
        return context;
    }
857840
@Override
    protected String doRequest(HttpRequestBase request) throws IOException {
        if(!request.getMethod().equals(HttpGet.METHOD_NAME) &&
                !this.getWsapiVersion().matches("^1[.]\\d+")) {
            try {
                attachSecurityInfo(request);
            } catch (URISyntaxException e) {
                throw new IOException("Unable to build URI with security token", e);
            }
        }
        return super.doRequest(request);
    }
700522
public static Map<String, String> getRequestHeaders(final HttpServletRequest request) {
        val headers = new LinkedHashMap<String, Object>();
        val headerNames = request.getHeaderNames();
        if (headerNames != null) {
            while (headerNames.hasMoreElements()) {
                val headerName = headerNames.nextElement();
                val headerValue = StringUtils.stripToEmpty(request.getHeader(headerName));
                headers.put(headerName, headerValue);
            }
        }
        return (Map) headers;
    }
655827
public Response request(final Request request) {
        request.setAuth(username, password);
        return httpClient.reliableRequest(request);
    }
819054
public static String readBody(HttpServletRequest request) {

        BufferedReader input = null;
        try {
            input = new BufferedReader(new InputStreamReader(request.getInputStream()));
            StringBuilder builder = new StringBuilder();
            String buffer;
            while ((buffer = input.readLine()) != null) {
                if (builder.length() > 0) {
                    builder.append("\n");
                }
                builder.append(buffer);
            }
            return builder.toString();
        } catch (IOException e) {
            log.info("http io exception : " + e.getMessage());
        }
        return null;
    }
1268340
public <T> Request<T> add(Request<T> request) {
        // Tag the request as belonging to this queue and add it to the set of current requests.
        request.setRequestQueue(this);
        synchronized (mCurrentRequests) {
            mCurrentRequests.add(request);
        }

        // Process requests in the order they are added.
        request.setSequence(getSequenceNumber());
        request.addMarker("add-to-queue");

        // If the request is uncacheable, skip the cache queue and go straight to the network.
        if (!request.shouldCache()) {
            mNetworkQueue.add(request);
            return request;
        }

        // Insert request into stage if there's already a request with the same cache key in flight.
        synchronized (mWaitingRequests) {
            String cacheKey = request.getCacheKey();
            if (mWaitingRequests.containsKey(cacheKey)) {
                // There is already a request in flight. Queue up.
                Queue<Request<?>> stagedRequests = mWaitingRequests.get(cacheKey);
                if (stagedRequests == null) {
                    stagedRequests = new LinkedList<Request<?>>();
                }
                stagedRequests.add(request);
                mWaitingRequests.put(cacheKey, stagedRequests);
                if (VolleyLog.DEBUG) {
                    VolleyLog.v("Request for cacheKey=%s is in flight, putting on hold.", cacheKey);
                }
            } else {
                // Insert 'null' queue for this cacheKey, indicating there is now a request in
                // flight.
                mWaitingRequests.put(cacheKey, null);
                mCacheQueue.add(request);
            }
            return request;
        }
    }
695234
public static String getRequestBody(HttpServletRequest request) {
		if(request.getMethod().equals("GET") || request.getMethod().equals("DELETE")) {
			return null;
		}
		
		StringBuilder stringBuilder = new StringBuilder();
		BufferedReader bufferedReader = null;
		try {
			InputStream inputStream = request.getInputStream();
			if (inputStream != null) {
				bufferedReader = new BufferedReader(new InputStreamReader(
						inputStream));
				char[] charBuffer = new char[128];
				int bytesRead = -1;
				while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
					stringBuilder.append(charBuffer, 0, bytesRead);
				}
			} else {
				stringBuilder.append("");
			}
		} catch (IOException ex) {
			// to nothing
		} finally {
			if (bufferedReader != null) {
				try {
					bufferedReader.close();
				} catch (IOException ex) {

				}
			}
		}

		if (!StringUtils.isEmpty(stringBuilder)) {
			return stringBuilder.toString();
		}

		if (request.getParameterMap().keySet().size() > 0) {
			return request.getParameterMap().keySet().toArray()[0].toString();
		}

        return null;
	}