Copy request headers from the servlet client to the proxy request.

@throws java.net.URISyntaxException
189523
private void copyRequestHeaders(HttpServletRequest servletRequest, HttpRequest proxyRequest)
            throws URISyntaxException {
        // Get an Enumeration of all of the header names sent by the client
        Enumeration<?> enumerationOfHeaderNames = servletRequest.getHeaderNames();
        while (enumerationOfHeaderNames.hasMoreElements()) {
            String headerName = (String) enumerationOfHeaderNames.nextElement();
            //Instead the content-length is effectively set via InputStreamEntity
            if (!headerName.equalsIgnoreCase(CONTENT_LENGTH) && !hopByHopHeaders.containsHeader(headerName)) {
                Enumeration<?> headers = servletRequest.getHeaders(headerName);
                while (headers.hasMoreElements()) {//sometimes more than one value
                    String headerValue = (String) headers.nextElement();
                    // In case the proxy host is running multiple virtual servers,
                    // rewrite the Host header to ensure that we get content from
                    // the correct virtual server
                    if (headerName.equalsIgnoreCase(HOST)) {
                        HttpHost host = URIUtils.extractHost(new URI(prerenderConfig.getPrerenderServiceUrl()));
                        headerValue = host.getHostName();
                        if (host.getPort() != -1) {
                            headerValue += ":" + host.getPort();
                        }
                    }
                    proxyRequest.addHeader(headerName, headerValue);
                }
            }
        }
    }
498807
void copyTo(RequestClientOptions target) {
        target.setReadLimit(getReadLimit());
        for (Marker marker: Marker.values())
            target.putClientMarker(marker, getClientMarker(marker));
    }
140755
public void setURI( String uriString, boolean encoded ) throws URISyntaxException
    {
        if ( uriString == null )
        {
            setScheme( null );
            setUserInfo( null );
            setHost( null );
            setPort( UNDEFINED_PORT );
            setPath( null );
            setQuery( null );
            setFragment( null );
        }
        else
        {
            URI uri = null;

            if ( encoded )
            {
                // Get (parse) the components using java.net.URI
                uri = new URI( uriString );
            }
            else
            {
                // Parse, then encode this string into its components using URI
                uri = encodeURI( uriString );
            }

            setURI( uri );
        }
    }
801603
private void setHttpRequestHeaders(MessageContext msgContext, HttpRequest httpRequest) {
    @SuppressWarnings("unchecked")
    Map<Object, Object> requestHeaders =
        (Map<Object, Object>) msgContext.getProperty(HTTPConstants.REQUEST_HEADERS);
    if (requestHeaders != null) {
      for (Entry<Object, Object> headerEntry : requestHeaders.entrySet()) {
        Object headerKey = headerEntry.getKey();
        if (headerKey == null) {
          continue;
        }
        String headerName = headerKey.toString().trim();
        Object headerValue = headerEntry.getValue();
        if (HTTPConstants.HEADER_AUTHORIZATION.equals(headerName)
            && (headerValue instanceof String)) {
          // HttpRequest expects the Authorization header to be a list of values,
          // so handle the case where it is simply a string.
          httpRequest.getHeaders().setAuthorization((String) headerValue);
        } else {
          httpRequest.getHeaders().set(headerName, headerValue);
        }
      }
    }
    if (msgContext.isPropertyTrue(HTTPConstants.MC_GZIP_REQUEST)) {
      httpRequest.getHeaders().setContentEncoding(HTTPConstants.COMPRESSION_GZIP);
    }
  }
634826
public void dumpRequest(final HttpServletRequest req) {
    try {
      Enumeration names = req.getHeaderNames();

      String title = "Request headers";

      debug(title);

      while (names.hasMoreElements()) {
        String key = (String)names.nextElement();
        String val = req.getHeader(key);
        debug("  " + key + " = \"" + val + "\"");
      }

      names = req.getParameterNames();

      title = "Request parameters";

      debug(title + " - global info and uris");
      debug("getRemoteAddr = " + req.getRemoteAddr());
      debug("getRequestURI = " + req.getRequestURI());
      debug("getRemoteUser = " + req.getRemoteUser());
      debug("getRequestedSessionId = " + req.getRequestedSessionId());
      debug("HttpUtils.getRequestURL(req) = " + req.getRequestURL());
      debug("contextPath=" + req.getContextPath());
      debug("query=" + req.getQueryString());
      debug("contentlen=" + req.getContentLength());
      debug("request=" + req);
      debug("parameters:");

      debug(title);

      while (names.hasMoreElements()) {
        String key = (String)names.nextElement();
        String val = req.getParameter(key);
        debug("  " + key + " = \"" + val + "\"");
      }
    } catch (Throwable t) {
    }
  }
773901
protected void addRequestHeaders(final HttpServletRequest httpServletRequest, final Map<String, List<Object>> attributes) {
        for (final Map.Entry<String, Set<String>> headerAttributeEntry : this.headerAttributeMapping.entrySet()) {
            final String headerName = headerAttributeEntry.getKey();
            final String value = httpServletRequest.getHeader(headerName);

            if (value != null) {
                for (final String attributeName : headerAttributeEntry.getValue()) {
                    attributes.put(attributeName,
                            headersToIgnoreSemicolons.contains(headerName) ?
                                    list(value)
                                    : splitOnSemiColonHandlingBackslashEscaping(value));
                }
            }
        }
    }
1115249
public <T extends J4pRequest> HttpUriRequest getHttpRequest(List<T> pRequests,Map<J4pQueryParameter,String> pProcessingOptions)
            throws UnsupportedEncodingException, URISyntaxException {
        JSONArray bulkRequest = new JSONArray();
        String queryParams = prepareQueryParameters(pProcessingOptions);
        HttpPost postReq = new HttpPost(createRequestURI(j4pServerUrl.getPath(),queryParams));
        for (T request : pRequests) {
            JSONObject requestContent = getJsonRequestContent(request);
            bulkRequest.add(requestContent);
        }
        postReq.setEntity(new StringEntity(bulkRequest.toJSONString(),"utf-8"));
        return postReq;
    }
1312338
@COPY
    @Timed
    public void copyResource(@Suspended final AsyncResponse response, @Context final Request request,
            @Context final UriInfo uriInfo, @Context final HttpHeaders headers,
            @Context final SecurityContext security) {
        final TrellisRequest req = new TrellisRequest(request, uriInfo, headers, security);
        final Session session = getSession(req.getPrincipalName());
        final IRI destination = getDestination(headers, getBaseUrl(req));
        final IRI identifier = rdf.createIRI(TRELLIS_DATA_PREFIX + req.getPath());
        // Default is recursive copy as per RFC-4918
        final Depth.DEPTH depth = getDepth(headers.getHeaderString("Depth"));
        getParent(destination).thenCombine(services.getResourceService().get(destination), this::checkResources)
            .thenCompose(parent -> services.getResourceService().touch(parent.getIdentifier()))
            .thenCompose(future -> services.getResourceService().get(identifier))
            .thenApply(this::checkResource)
            .thenCompose(res -> copyTo(res, session, depth, destination, getBaseUrl(req)))
            .thenApply(future -> status(NO_CONTENT).build())
            .exceptionally(this::handleException).thenApply(response::resume);
    }
1350189
private void executeProxyRequest(HttpMethod httpMethodProxyRequest,
                                     HttpServletRequest httpServletRequest,
                                     HttpServletResponse httpServletResponse, History history) {
        try {
            RequestInformation requestInfo = requestInformation.get();

            // Execute the request

            // set virtual host so the server knows how to direct the request
            // If the host header exists then this uses that value
            // Otherwise the hostname from the URL is used
            processVirtualHostName(httpMethodProxyRequest, httpServletRequest);
            cullDisabledPaths();

            // check for existence of ODO_PROXY_HEADER
            // finding it indicates a bad loop back through the proxy
            if (httpServletRequest.getHeader(Constants.ODO_PROXY_HEADER) != null) {
                logger.error("Request has looped back into the proxy.  This will not be executed: {}", httpServletRequest.getRequestURL());
                return;
            }

            // set ODO_PROXY_HEADER
            httpMethodProxyRequest.addRequestHeader(Constants.ODO_PROXY_HEADER, "proxied");

            requestInfo.blockRequest = hasRequestBlock();
            PluginResponse responseWrapper = new PluginResponse(httpServletResponse);
            requestInfo.jsonpCallback = stripJSONPToOutstr(httpServletRequest, responseWrapper);

            if (!requestInfo.blockRequest) {
                logger.info("Sending request to server");

                history.setModified(requestInfo.modified);
                history.setRequestSent(true);

                executeRequest(httpMethodProxyRequest,
                               httpServletRequest,
                               responseWrapper,
                               history);
            } else {
                history.setRequestSent(false);
            }

            logOriginalResponseHistory(responseWrapper, history);
            applyResponseOverrides(responseWrapper, httpServletRequest, httpMethodProxyRequest, history);
            // store history
            history.setModified(requestInfo.modified);
            logRequestHistory(httpMethodProxyRequest, responseWrapper, history);

            writeResponseOutput(responseWrapper, requestInfo.jsonpCallback);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
756809
protected void setupHTTPRequestHeaderProperties(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
    {
        //setup header properties
        Properties headerProperties=httpRequest.getHeaderProperties();
        if(headerProperties!=null)
        {
            Iterator<Entry<Object,Object>> iterator=headerProperties.entrySet().iterator();
            Entry<Object,Object> entry=null;
            while(iterator.hasNext())
            {
                //get next entry
                entry=iterator.next();
                
                //set header values
                httpMethodClient.addRequestHeader((String)entry.getKey(),(String)entry.getValue());
            }
        }
    }
1113651
private IoBuffer encodeProxyRequestPacket(final SocksProxyRequest request)
            throws UnsupportedEncodingException {
        int len = 6;
        InetSocketAddress adr = request.getEndpointAddress();
        byte addressType = 0;
        byte[] host = null;
        
        if (adr != null && !adr.isUnresolved()) {
            if (adr.getAddress() instanceof Inet6Address) {
                len += 16;
                addressType = SocksProxyConstants.IPV6_ADDRESS_TYPE;
            } else if (adr.getAddress() instanceof Inet4Address) {
                len += 4;
                addressType = SocksProxyConstants.IPV4_ADDRESS_TYPE;
            }
        } else {
            host = request.getHost() != null ? 
                    request.getHost().getBytes("ASCII") : null;

            if (host != null) {
                len += 1 + host.length;
                addressType = SocksProxyConstants.DOMAIN_NAME_ADDRESS_TYPE;
            } else {
                throw new IllegalArgumentException("SocksProxyRequest object " +
                        "has no suitable endpoint information");
            }
        }
        
        IoBuffer buf = IoBuffer.allocate(len);

        buf.put(request.getProtocolVersion());
        buf.put(request.getCommandCode());
        buf.put((byte) 0x00); // Reserved
        buf.put(addressType);

        if (host == null) {
            buf.put(request.getIpAddress());
        } else {
            buf.put((byte) host.length);
            buf.put(host);            
        }

        buf.put(request.getPort());

        return buf;
    }
579815
private void copyHeadersFromClient(HttpServletRequest pRequest, HttpURLConnection pRemoteConnection) {
        Enumeration headerNames = pRequest.getHeaderNames();
        while (headerNames.hasMoreElements()) {
            String headerName = (String) headerNames.nextElement();
            Enumeration headerValues = pRequest.getHeaders(headerName);

            // Skip the "host" header, as we want something else
            if (HTTP_REQUEST_HEADER_HOST.equalsIgnoreCase(headerName)) {
                // Skip this header
                headerName = null;
            }

            // Set the the header to the remoteConnection
            if (headerName != null) {
                // Convert from multiple line to single line, comma separated, as
                // there seems to be a shortcoming in the URLConneciton API...
                StringBuilder headerValue = new StringBuilder();
                while (headerValues.hasMoreElements()) {
                    String value = (String) headerValues.nextElement();
                    headerValue.append(value);
                    if (headerValues.hasMoreElements()) {
                        headerValue.append(", ");
                    }
                }

                //System.out.println("client -->>> remote: " + headerName + ": " + headerValue);
                pRemoteConnection.setRequestProperty(headerName, headerValue.toString());
            }
        }
    }
96921
private void setHeaders(XMLHttpRequest xmlHttpRequest) throws RequestException {

        if ((headers != null) && (headers.size() > 0)) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                try {
                    xmlHttpRequest.setRequestHeader(header.getKey(), header.getValue());
                } catch (JavaScriptException e) {
                    throw new RequestException(e.getMessage());
                }
            }
        } else {
            xmlHttpRequest.setRequestHeader("Content-Type", "text/plain; charset=utf-8");
        }
    }
578843
private byte[] copyBytesFromRequest(HttpServletRequest httpServletRequest) throws IOException {
        InputStream inputStream = httpServletRequest.getInputStream();
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int offset=-1;
        while((offset=inputStream.read(buffer,0,1024))>0){
            byteArrayOutputStream.write(buffer,0,offset);
        }
        return byteArrayOutputStream.toByteArray();
    }
806486
@Override
	protected boolean copyRequestedContentToResponse(String requestedPath, HttpServletResponse response,
			String contentType) throws IOException {

		boolean copyDone = false;
		if (isValidRequestedPath(requestedPath)) {

			try {
				writeContent(requestedPath, null, response);
				response.setContentType(contentType);
				copyDone = true;
			} catch (ResourceNotFoundException e) {
				// Nothing to do here
			}
		}

		return copyDone;
	}
594600
protected void setRequestContent(HTTPRequest httpRequest,HttpMethodBase httpMethodClient)
    {
        //set content
        if(httpMethodClient instanceof EntityEnclosingMethod)
        {
            EntityEnclosingMethod pushMethod=(EntityEnclosingMethod)httpMethodClient;
            
            RequestEntity requestEntity=null;
            ContentType contentType=httpRequest.getContentType();
            switch(contentType)
            {
                case STRING:
                    requestEntity=this.createStringRequestContent(httpRequest);
                    break;
                case BINARY:
                    requestEntity=this.createBinaryRequestContent(httpRequest);
                    break;
                case MULTI_PART:
                    requestEntity=this.createMultiPartRequestContent(httpRequest,httpMethodClient);
                    break;
                default:
                    throw new FaxException("Unsupported content type: "+contentType);
            }

            //set request data
            if(requestEntity!=null)
            {
                pushMethod.setRequestEntity(requestEntity);
                pushMethod.setContentChunked(false);
            }
        }
    }
35577
static void copyResources(URL resourceUrl, File targetPath) throws IOException, URISyntaxException {
        if (resourceUrl == null) {
            return;
        }

        URLConnection urlConnection = resourceUrl.openConnection();

        /**
         * Copy resources either from inside jar or from project folder.
         */
        if (urlConnection instanceof JarURLConnection) {
            copyJarResourceToPath((JarURLConnection) urlConnection, targetPath);
        } else if (VFS_PROTOCOL.equals(resourceUrl.getProtocol())) {
            VirtualFile virtualFileOrFolder = VFS.getChild(resourceUrl.toURI());
            copyFromWarToFolder(virtualFileOrFolder, targetPath);
        } else {
            File file = new File(resourceUrl.getPath());
            if (file.isDirectory()) {
                for (File resourceFile : FileUtils.listFiles(file, null, true)) {
                    int index = resourceFile.getPath().lastIndexOf(targetPath.getName()) + targetPath.getName().length();
                    File targetFile = new File(targetPath, resourceFile.getPath().substring(index));
                    if (!targetFile.exists() || targetFile.length() != resourceFile.length()) {
                        if (resourceFile.isFile()) {
                            FileUtils.copyFile(resourceFile, targetFile);
                        }
                    }
                }
            } else {
                if (!targetPath.exists() || targetPath.length() != file.length()) {
                    FileUtils.copyFile(file, targetPath);
                }
            }
        }
    }