Example usage for org.apache.commons.httpclient HttpMethod setDoAuthentication

List of usage examples for org.apache.commons.httpclient HttpMethod setDoAuthentication

Introduction

In this page you can find the example usage for org.apache.commons.httpclient HttpMethod setDoAuthentication.

Prototype

public abstract void setDoAuthentication(boolean paramBoolean);

Source Link

Usage

From source file:io.fabric8.gateway.servlet.ProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link javax.servlet.http.HttpServletResponse}
 *
 * @param proxyDetails//from  www.  ja v  a2  s  .com
 * @param httpMethodProxyRequest An object representing the proxy request to be made
 * @param httpServletResponse    An object by which we can send the proxied
 *                               response back to the client
 * @throws java.io.IOException            Can be thrown by the {@link HttpClient}.executeMethod
 * @throws javax.servlet.ServletException Can be thrown to indicate that another error has occurred
 */
private void executeProxyRequest(ProxyDetails proxyDetails, HttpMethod httpMethodProxyRequest,
        HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse)
        throws IOException, ServletException {
    httpMethodProxyRequest.setDoAuthentication(false);
    httpMethodProxyRequest.setFollowRedirects(false);

    // Create a default HttpClient
    HttpClient httpClient = proxyDetails.createHttpClient(httpMethodProxyRequest);

    // Execute the request
    int intProxyResponseCode = httpClient.executeMethod(httpMethodProxyRequest);

    // Check if the proxy response is a redirect
    // The following code is adapted from org.tigris.noodle.filters.CheckForRedirect
    // Hooray for open source software
    if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
            && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
        String stringStatusCode = Integer.toString(intProxyResponseCode);
        String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
        if (stringLocation == null) {
            throw new ServletException("Received status code: " + stringStatusCode + " but no "
                    + STRING_LOCATION_HEADER + " header was found in the response");
        }
        // Modify the redirect to go to this proxy servlet rather that the proxied host
        String stringMyHostName = httpServletRequest.getServerName();
        if (httpServletRequest.getServerPort() != 80) {
            stringMyHostName += ":" + httpServletRequest.getServerPort();
        }
        stringMyHostName += httpServletRequest.getContextPath();
        httpServletResponse.sendRedirect(stringLocation
                .replace(proxyDetails.getProxyHostAndPort() + proxyDetails.getProxyPath(), stringMyHostName));
        return;
    } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
        // 304 needs special handling.  See:
        // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
        // We get a 304 whenever passed an 'If-Modified-Since'
        // header and the data on disk has not changed; server
        // responds w/ a 304 saying I'm not going to send the
        // body because the file has not changed.
        httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
        httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
        return;
    }

    // Pass the response code back to the client
    httpServletResponse.setStatus(intProxyResponseCode);

    // Pass response headers back to the client
    Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
    for (Header header : headerArrayResponse) {
        if (!ProxySupport.isHopByHopHeader(header.getName())) {
            if (ProxySupport.isSetCookieHeader(header)) {
                HttpProxyRule proxyRule = proxyDetails.getProxyRule();
                String setCookie = ProxySupport.replaceCookieAttributes(header.getValue(),
                        proxyRule.getCookiePath(), proxyRule.getCookieDomain());
                httpServletResponse.setHeader(header.getName(), setCookie);
            } else {
                httpServletResponse.setHeader(header.getName(), header.getValue());
            }
        }
    }

    // check if we got data, that is either the Content-Length > 0
    // or the response code != 204
    int code = httpMethodProxyRequest.getStatusCode();
    boolean noData = code == HttpStatus.SC_NO_CONTENT;
    if (!noData) {
        String length = httpServletRequest.getHeader(STRING_CONTENT_LENGTH_HEADER_NAME);
        if (length != null && "0".equals(length.trim())) {
            noData = true;
        }
    }
    LOG.trace("Response has data? {}", !noData);

    if (!noData) {
        // Send the content to the client
        InputStream inputStreamProxyResponse = httpMethodProxyRequest.getResponseBodyAsStream();
        BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStreamProxyResponse);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        int intNextByte;
        while ((intNextByte = bufferedInputStream.read()) != -1) {
            outputStreamClientResponse.write(intNextByte);
        }
    }
}

From source file:de.innovationgate.webgate.api.rss2.SimpleRSS.java

private InputStream retrievePage(String url, NativeQueryOptions nativeOptions) throws WGQueryException {

    try {/*from  ww w .  java  2  s .c om*/

        // Retrieve from web
        HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
        client.setConnectionTimeout(10000);
        if (_useProxy) {
            client.getHostConfiguration().setProxy(_proxyHost, _proxyPort);
            if (_proxyCredentials != null) {
                Credentials credentials;
                if (_proxyDomain != null) {
                    List elements = WGUtils.deserializeCollection(_proxyCredentials, ":");
                    credentials = new NTCredentials((String) elements.get(0), (String) elements.get(1),
                            _proxyHost, _proxyDomain);
                } else {
                    credentials = new UsernamePasswordCredentials(_proxyCredentials);

                }
                client.getState().setProxyCredentials(null, _proxyHost, credentials);

            }
        }
        HttpMethod method = new GetMethod(url);
        method.setFollowRedirects(true);
        method.setStrictMode(false);

        if (nativeOptions.containsKey(QUERYOPTION_USER) && nativeOptions.containsKey(QUERYOPTION_PWD)) {
            method.setDoAuthentication(true);
            client.getParams().setAuthenticationPreemptive(true);
            client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    nativeOptions.get(QUERYOPTION_USER), nativeOptions.get(QUERYOPTION_PWD)));
        }

        client.executeMethod(method);

        // Read response. Wrap content decoder if necessary.
        InputStream inStream = method.getResponseBodyAsStream();

        // Return InputStream from given URL
        return inStream;
    } catch (MalformedURLException e) {
        throw new WGQueryException("Malformed feed URL", url, e);
    } catch (IOException e) {
        throw new WGQueryException("IO Exception retrieving feed", url, e);
    }
}

From source file:fedora.client.test.PerformanceTests.java

private HttpMethod getHttpMethod(String pid) {
    String url = "http://" + host + ":" + port + "/" + context + "/get/" + pid + "/" + "MDS1";
    HttpMethod httpMethod = new GetMethod(url);
    httpMethod.setDoAuthentication(true);
    httpMethod.getParams().setParameter("Connection", "Keep-Alive");
    return httpMethod;
}

From source file:fedora.test.api.TestRESTAPI.java

private HttpResponse getOrDelete(String method, boolean authenticate) throws Exception {
    if (url == null || url.length() == 0) {
        throw new IllegalArgumentException("url must be a non-empty value");
    } else if (!(url.startsWith("http://") || url.startsWith("https://"))) {
        url = getBaseURL() + url;//from ww w  . java 2 s .  c  o m
    }
    HttpMethod httpMethod = null;
    try {
        if (method.equals("GET")) {
            httpMethod = new GetMethod(url);
        } else if (method.equals("DELETE")) {
            httpMethod = new DeleteMethod(url);
        } else {
            throw new IllegalArgumentException("method must be one of GET or DELETE.");
        }

        httpMethod.setDoAuthentication(authenticate);
        httpMethod.getParams().setParameter("Connection", "Keep-Alive");
        getClient(authenticate).executeMethod(httpMethod);
        return new HttpResponse(httpMethod);
    } finally {
        if (httpMethod != null) {
            httpMethod.releaseConnection();
        }
    }
}

From source file:com.twinsoft.convertigo.beans.connectors.HttpConnector.java

protected int doExecuteMethod(final HttpMethod method, Context context)
        throws ConnectionException, URIException, MalformedURLException {
    int statuscode = -1;

    // Tells the method to automatically handle authentication.
    method.setDoAuthentication(true);

    // Tells the method to automatically handle redirection.
    method.setFollowRedirects(false);// ww w . j  a va2s.c o m

    HttpPool httpPool = ((AbstractHttpTransaction) context.transaction).getHttpPool();
    HttpClient httpClient = context.getHttpClient3(httpPool);

    try {
        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logBeans.isTraceEnabled())
                Engine.logBeans.trace(
                        "(HttpConnector) HttpClient request cookies:" + Arrays.asList(cookies).toString());
        }

        forwardHeader(new HeaderForwarder() {
            public void add(String name, String value, String forwardPolicy) {
                if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_IGNORE.equals(forwardPolicy)) {
                    Header exHeader = method.getRequestHeader(name);
                    if (exHeader != null) {
                        // Nothing to do
                        Engine.logEngine.debug("(WebViewer) Forwarding header '" + name
                                + "' has been ignored due to forward policy");
                    } else {
                        method.setRequestHeader(name, value);
                        Engine.logEngine.debug("(WebViewer) Header forwarded and added: " + name + "=" + value);
                    }
                } else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_REPLACE.equals(forwardPolicy)) {
                    method.setRequestHeader(name, value);
                    Engine.logEngine.debug("(WebViewer) Header forwarded and replaced: " + name + "=" + value);
                } else if (HttpConnector.HTTP_HEADER_FORWARD_POLICY_MERGE.equals(forwardPolicy)) {
                    Header exHeader = method.getRequestHeader(name);
                    if (exHeader != null)
                        value = exHeader.getValue() + ", " + value;

                    method.setRequestHeader(name, value);
                    Engine.logEngine.debug("(WebViewer) Header forwarded and merged: " + name + "=" + value);
                }
            }
        });

        // handle oAuthSignatures if any
        if (oAuthKey != null && oAuthSecret != null && oAuthToken != null && oAuthTokenSecret != null) {
            oAuthConsumer = new HttpOAuthConsumer(oAuthKey, oAuthSecret, hostConfiguration);
            oAuthConsumer.setTokenWithSecret(oAuthToken, oAuthTokenSecret);
            oAuthConsumer.sign(method);

            oAuthConsumer = null;
        }

        HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool);

        hostConfiguration.getParams().setIntParameter(HttpConnectionParams.SO_TIMEOUT,
                (int) context.requestedObject.getResponseTimeout() * 1000);
        hostConfiguration.getParams().setIntParameter(HttpConnectionParams.CONNECTION_TIMEOUT,
                (int) context.requestedObject.getResponseTimeout() * 1000);

        Engine.logBeans.debug("(HttpConnector) HttpClient: executing method...");
        statuscode = httpClient.executeMethod(hostConfiguration, method, httpState);
        Engine.logBeans.debug("(HttpConnector) HttpClient: end of method successfull");

        // Display the cookies
        if (handleCookie) {
            Cookie[] cookies = httpState.getCookies();
            if (Engine.logBeans.isTraceEnabled())
                Engine.logBeans.trace(
                        "(HttpConnector) HttpClient response cookies:" + Arrays.asList(cookies).toString());
        }
    } catch (SocketTimeoutException e) {
        throw new ConnectionException(
                "Timeout reached (" + context.requestedObject.getResponseTimeout() + " sec)");
    } catch (IOException e) {
        if (!context.requestedObject.runningThread.bContinue)
            return statuscode;

        try {
            HttpUtils.logCurrentHttpConnection(httpClient, hostConfiguration, httpPool);
            Engine.logBeans.warn("(HttpConnector) HttpClient: connection error to " + sUrl + ": "
                    + e.getMessage() + "; retrying method");
            statuscode = httpClient.executeMethod(hostConfiguration, method, httpState);
            Engine.logBeans.debug("(HttpConnector) HttpClient: end of method successfull");
        } catch (IOException ee) {
            throw new ConnectionException("Connection error to " + sUrl, ee);
        }
    } catch (OAuthException eee) {
        throw new ConnectionException("OAuth Connection error to " + sUrl, eee);
    }
    return statuscode;
}

From source file:com.zimbra.cs.zimlet.ProxyServlet.java

private void doProxy(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    ZimbraLog.clearContext();/*  w w w .jav  a 2  s  .  com*/
    boolean isAdmin = isAdminRequest(req);
    AuthToken authToken = isAdmin ? getAdminAuthTokenFromCookie(req, resp, true)
            : getAuthTokenFromCookie(req, resp, true);
    if (authToken == null) {
        String zAuthToken = req.getParameter(QP_ZAUTHTOKEN);
        if (zAuthToken != null) {
            try {
                authToken = AuthProvider.getAuthToken(zAuthToken);
                if (authToken.isExpired()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken expired");
                    return;
                }
                if (!authToken.isRegistered()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "authtoken is invalid");
                    return;
                }
                if (isAdmin && !authToken.isAdmin()) {
                    resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "permission denied");
                    return;
                }
            } catch (AuthTokenException e) {
                resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "unable to parse authtoken");
                return;
            }
        }
    }
    if (authToken == null) {
        resp.sendError(HttpServletResponse.SC_UNAUTHORIZED, "no authtoken cookie");
        return;
    }

    // get the posted body before the server read and parse them.
    byte[] body = copyPostedData(req);

    // sanity check
    String target = req.getParameter(TARGET_PARAM);
    if (target == null) {
        resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
        return;
    }

    // check for permission
    URL url = new URL(target);
    if (!isAdmin && !checkPermissionOnTarget(url, authToken)) {
        resp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }

    // determine whether to return the target inline or store it as an upload
    String uploadParam = req.getParameter(UPLOAD_PARAM);
    boolean asUpload = uploadParam != null && (uploadParam.equals("1") || uploadParam.equalsIgnoreCase("true"));

    HttpMethod method = null;
    try {
        HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
        HttpProxyUtil.configureProxy(client);
        String reqMethod = req.getMethod();
        if (reqMethod.equalsIgnoreCase("GET")) {
            method = new GetMethod(target);
        } else if (reqMethod.equalsIgnoreCase("POST")) {
            PostMethod post = new PostMethod(target);
            if (body != null)
                post.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = post;
        } else if (reqMethod.equalsIgnoreCase("PUT")) {
            PutMethod put = new PutMethod(target);
            if (body != null)
                put.setRequestEntity(new ByteArrayRequestEntity(body, req.getContentType()));
            method = put;
        } else if (reqMethod.equalsIgnoreCase("DELETE")) {
            method = new DeleteMethod(target);
        } else {
            ZimbraLog.zimlet.info("unsupported request method: " + reqMethod);
            resp.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
            return;
        }

        // handle basic auth
        String auth, user, pass;
        auth = req.getParameter(AUTH_PARAM);
        user = req.getParameter(USER_PARAM);
        pass = req.getParameter(PASS_PARAM);
        if (auth != null && user != null && pass != null) {
            if (!auth.equals(AUTH_BASIC)) {
                ZimbraLog.zimlet.info("unsupported auth type: " + auth);
                resp.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            HttpState state = new HttpState();
            state.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(user, pass));
            client.setState(state);
            method.setDoAuthentication(true);
        }

        Enumeration headers = req.getHeaderNames();
        while (headers.hasMoreElements()) {
            String hdr = (String) headers.nextElement();
            ZimbraLog.zimlet.debug("incoming: " + hdr + ": " + req.getHeader(hdr));
            if (canProxyHeader(hdr)) {
                ZimbraLog.zimlet.debug("outgoing: " + hdr + ": " + req.getHeader(hdr));
                if (hdr.equalsIgnoreCase("x-host"))
                    method.getParams().setVirtualHost(req.getHeader(hdr));
                else
                    method.addRequestHeader(hdr, req.getHeader(hdr));
            }
        }

        try {
            if (!(reqMethod.equalsIgnoreCase("POST") || reqMethod.equalsIgnoreCase("PUT"))) {
                method.setFollowRedirects(true);
            }
            HttpClientUtil.executeMethod(client, method);
        } catch (HttpException ex) {
            ZimbraLog.zimlet.info("exception while proxying " + target, ex);
            resp.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        int status = method.getStatusLine() == null ? HttpServletResponse.SC_INTERNAL_SERVER_ERROR
                : method.getStatusCode();

        // workaround for Alexa Thumbnails paid web service, which doesn't bother to return a content-type line
        Header ctHeader = method.getResponseHeader("Content-Type");
        String contentType = ctHeader == null || ctHeader.getValue() == null ? DEFAULT_CTYPE
                : ctHeader.getValue();

        InputStream targetResponseBody = method.getResponseBodyAsStream();

        if (asUpload) {
            String filename = req.getParameter(FILENAME_PARAM);
            if (filename == null || filename.equals(""))
                filename = new ContentType(contentType).getParameter("name");
            if ((filename == null || filename.equals(""))
                    && method.getResponseHeader("Content-Disposition") != null)
                filename = new ContentDisposition(method.getResponseHeader("Content-Disposition").getValue())
                        .getParameter("filename");
            if (filename == null || filename.equals(""))
                filename = "unknown";

            List<Upload> uploads = null;

            if (targetResponseBody != null) {
                try {
                    Upload up = FileUploadServlet.saveUpload(targetResponseBody, filename, contentType,
                            authToken.getAccountId());
                    uploads = Arrays.asList(up);
                } catch (ServiceException e) {
                    if (e.getCode().equals(MailServiceException.UPLOAD_REJECTED))
                        status = HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE;
                    else
                        status = HttpServletResponse.SC_INTERNAL_SERVER_ERROR;
                }
            }

            resp.setStatus(status);
            FileUploadServlet.sendResponse(resp, status, req.getParameter(FORMAT_PARAM), null, uploads, null);
        } else {
            resp.setStatus(status);
            resp.setContentType(contentType);
            for (Header h : method.getResponseHeaders())
                if (canProxyHeader(h.getName()))
                    resp.addHeader(h.getName(), h.getValue());
            if (targetResponseBody != null)
                ByteUtil.copy(targetResponseBody, true, resp.getOutputStream(), true);
        }
    } finally {
        if (method != null)
            method.releaseConnection();
    }
}

From source file:com.twinsoft.convertigo.engine.servlets.ReverseProxyServlet.java

/**
 * Executes the {@link HttpMethod} passed in and sends the proxy response
 * back to the client via the given {@link HttpServletResponse}
 * /*from   w w  w .j a  v  a  2s  .  co  m*/
 * @param httpMethodProxyRequest
 *            An object representing the proxy request to be made
 * @param httpServletResponse
 *            An object by which we can send the proxied response back to
 *            the client
 * @throws IOException
 *             Can be thrown by the {@link HttpClient}.executeMethod
 * @throws ServletException
 *             Can be thrown to indicate that another error has occurred
 * @throws EngineException
 */
private void doRequest(HttpMethodType httpMethodType, HttpServletRequest httpServletRequest,
        HttpServletResponse httpServletResponse) throws IOException, ServletException {
    try {
        Engine.logEngine.debug("(ReverseProxyServlet) Starting request handling");

        if (Boolean.parseBoolean(EnginePropertiesManager.getProperty(PropertyName.SSL_DEBUG))) {
            System.setProperty("javax.net.debug", "all");
            Engine.logEngine.trace("(ReverseProxyServlet) Enabling SSL debug mode");
        } else {
            System.setProperty("javax.net.debug", "");
            Engine.logEngine.debug("(ReverseProxyServlet) Disabling SSL debug mode");
        }

        String baseUrl;
        String projectName;
        String connectorName;
        String contextName;
        String extraPath;

        {
            String requestURI = httpServletRequest.getRequestURI();
            Engine.logEngine.trace("(ReverseProxyServlet) Requested URI : " + requestURI);
            Matcher m = reg_fields.matcher(requestURI);
            if (m.matches() && m.groupCount() >= 5) {
                baseUrl = m.group(1);
                projectName = m.group(2);
                connectorName = m.group(3);
                contextName = m.group(4);
                extraPath = m.group(5);
            } else {
                throw new MalformedURLException(
                        "The request doesn't contains needed fields : projectName, connectorName and contextName");
            }
        }

        String sessionID = httpServletRequest.getSession().getId();

        Engine.logEngine.debug("(ReverseProxyServlet) baseUrl : " + baseUrl + " ; projectName : " + projectName
                + " ; connectorName : " + connectorName + " ; contextName : " + contextName + " ; extraPath : "
                + extraPath + " ; sessionID : " + sessionID);

        Context context = Engine.theApp.contextManager.get(null, contextName, sessionID, null, projectName,
                connectorName, null);

        Project project = Engine.theApp.databaseObjectsManager.getProjectByName(projectName);
        context.projectName = projectName;
        context.project = project;

        ProxyHttpConnector proxyHttpConnector = (ProxyHttpConnector) project.getConnectorByName(connectorName);
        context.connector = proxyHttpConnector;
        context.connectorName = proxyHttpConnector.getName();

        HostConfiguration hostConfiguration = proxyHttpConnector.hostConfiguration;

        // Proxy configuration
        String proxyServer = Engine.theApp.proxyManager.getProxyServer();
        String proxyUser = Engine.theApp.proxyManager.getProxyUser();
        String proxyPassword = Engine.theApp.proxyManager.getProxyPassword();
        int proxyPort = Engine.theApp.proxyManager.getProxyPort();

        if (!proxyServer.equals("")) {
            hostConfiguration.setProxy(proxyServer, proxyPort);
            Engine.logEngine.debug("(ReverseProxyServlet) Using proxy: " + proxyServer + ":" + proxyPort);
        } else {
            // Remove old proxy configuration
            hostConfiguration.setProxyHost(null);
        }

        String targetHost = proxyHttpConnector.getServer();
        Engine.logEngine.debug("(ReverseProxyServlet) Target host: " + targetHost);
        int targetPort = proxyHttpConnector.getPort();
        Engine.logEngine.debug("(ReverseProxyServlet) Target port: " + targetPort);

        // Configuration SSL
        Engine.logEngine.debug("(ReverseProxyServlet) Https: " + proxyHttpConnector.isHttps());
        CertificateManager certificateManager = proxyHttpConnector.certificateManager;
        boolean trustAllServerCertificates = proxyHttpConnector.isTrustAllServerCertificates();

        if (proxyHttpConnector.isHttps()) {
            Engine.logEngine.debug("(ReverseProxyServlet) Setting up SSL properties");
            certificateManager.collectStoreInformation(context);

            Engine.logEngine.debug(
                    "(ReverseProxyServlet) CertificateManager has changed: " + certificateManager.hasChanged);
            if (certificateManager.hasChanged || (!targetHost.equalsIgnoreCase(hostConfiguration.getHost()))
                    || (hostConfiguration.getPort() != targetPort)) {
                Engine.logEngine
                        .debug("(ReverseProxyServlet) Using MySSLSocketFactory for creating the SSL socket");
                Protocol myhttps = new Protocol("https",
                        MySSLSocketFactory.getSSLSocketFactory(certificateManager.keyStore,
                                certificateManager.keyStorePassword, certificateManager.trustStore,
                                certificateManager.trustStorePassword, trustAllServerCertificates),
                        targetPort);

                hostConfiguration.setHost(targetHost, targetPort, myhttps);
            }

            Engine.logEngine.debug("(ReverseProxyServlet) Updated host configuration for SSL purposes");
        } else {
            hostConfiguration.setHost(targetHost, targetPort);
        }

        HttpMethod httpMethodProxyRequest;

        String targetPath = proxyHttpConnector.getBaseDir() + extraPath;

        // Handle the query string
        if (httpServletRequest.getQueryString() != null) {
            targetPath += "?" + httpServletRequest.getQueryString();
        }
        Engine.logEngine.debug("(ReverseProxyServlet) Target path: " + targetPath);

        Engine.logEngine.debug("(ReverseProxyServlet) Requested method: " + httpMethodType);

        if (httpMethodType == HttpMethodType.GET) {
            // Create a GET request
            httpMethodProxyRequest = new GetMethod();
        } else if (httpMethodType == HttpMethodType.POST) {
            // Create a standard POST request
            httpMethodProxyRequest = new PostMethod();
            ((PostMethod) httpMethodProxyRequest)
                    .setRequestEntity(new InputStreamRequestEntity(httpServletRequest.getInputStream()));
        } else {
            throw new IllegalArgumentException("Unknown HTTP method: " + httpMethodType);
        }

        String charset = httpMethodProxyRequest.getParams().getUriCharset();
        URI targetURI;
        try {
            targetURI = new URI(targetPath, true, charset);
        } catch (URIException e) {
            // Bugfix #1484
            String newTargetPath = "";
            for (String part : targetPath.split("&")) {
                if (!newTargetPath.equals("")) {
                    newTargetPath += "&";
                }
                String[] pair = part.split("=");
                try {
                    newTargetPath += URLDecoder.decode(pair[0], "UTF-8") + "="
                            + (pair.length > 1 ? URLEncoder.encode(URLDecoder.decode(pair[1], "UTF-8"), "UTF-8")
                                    : "");
                } catch (UnsupportedEncodingException ee) {
                    newTargetPath = targetPath;
                }
            }

            targetURI = new URI(newTargetPath, true, charset);
        }
        httpMethodProxyRequest.setURI(targetURI);

        // Tells the method to automatically handle authentication.
        httpMethodProxyRequest.setDoAuthentication(true);

        HttpState httpState = getHttpState(proxyHttpConnector, context);

        String basicUser = proxyHttpConnector.getAuthUser();
        String basicPassword = proxyHttpConnector.getAuthPassword();
        String givenBasicUser = proxyHttpConnector.getGivenAuthUser();
        String givenBasicPassword = proxyHttpConnector.getGivenAuthPassword();

        // Basic authentication configuration
        String realm = null;
        if (!basicUser.equals("") || (basicUser.equals("") && (givenBasicUser != null))) {
            String userName = ((givenBasicUser == null) ? basicUser : givenBasicUser);
            String userPassword = ((givenBasicPassword == null) ? basicPassword : givenBasicPassword);
            httpState.setCredentials(new AuthScope(targetHost, targetPort, realm),
                    new UsernamePasswordCredentials(userName, userPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Credentials: " + userName + ":******");
        }

        // Setting basic authentication for proxy
        if (!proxyServer.equals("") && !proxyUser.equals("")) {
            httpState.setProxyCredentials(new AuthScope(proxyServer, proxyPort),
                    new UsernamePasswordCredentials(proxyUser, proxyPassword));
            Engine.logEngine.debug("(ReverseProxyServlet) Proxy credentials: " + proxyUser + ":******");
        }

        // Forward the request headers
        setProxyRequestHeaders(httpServletRequest, httpMethodProxyRequest, proxyHttpConnector);

        // Use the CEMS HttpClient
        HttpClient httpClient = Engine.theApp.httpClient;
        httpMethodProxyRequest.setFollowRedirects(false);

        // Execute the request
        int intProxyResponseCode = httpClient.executeMethod(hostConfiguration, httpMethodProxyRequest,
                httpState);

        // Check if the proxy response is a redirect
        // The following code is adapted from
        // org.tigris.noodle.filters.CheckForRedirect
        // Hooray for open source software
        if (intProxyResponseCode >= HttpServletResponse.SC_MULTIPLE_CHOICES /* 300 */
                && intProxyResponseCode < HttpServletResponse.SC_NOT_MODIFIED /* 304 */) {
            String stringStatusCode = Integer.toString(intProxyResponseCode);
            String stringLocation = httpMethodProxyRequest.getResponseHeader(STRING_LOCATION_HEADER).getValue();
            if (stringLocation == null) {
                throw new ServletException("Received status code: " + stringStatusCode + " but no "
                        + STRING_LOCATION_HEADER + " header was found in the response");
            }
            // Modify the redirect to go to this proxy servlet rather that
            // the
            // proxied host
            String redirect = handleRedirect(stringLocation, baseUrl, proxyHttpConnector);
            httpServletResponse.sendRedirect(redirect);
            Engine.logEngine.debug("(ReverseProxyServlet) Send redirect (" + redirect + ")");
            return;
        } else if (intProxyResponseCode == HttpServletResponse.SC_NOT_MODIFIED) {
            // 304 needs special handling. See:
            // http://www.ics.uci.edu/pub/ietf/http/rfc1945.html#Code304
            // We get a 304 whenever passed an 'If-Modified-Since'
            // header and the data on disk has not changed; server
            // responds w/ a 304 saying I'm not going to send the
            // body because the file has not changed.
            httpServletResponse.setIntHeader(STRING_CONTENT_LENGTH_HEADER_NAME, 0);
            httpServletResponse.setStatus(HttpServletResponse.SC_NOT_MODIFIED);
            Engine.logEngine.debug("(ReverseProxyServlet) NOT MODIFIED (304)");
            return;
        }

        // Pass the response code back to the client
        httpServletResponse.setStatus(intProxyResponseCode);

        // Pass response headers back to the client
        Engine.logEngine.debug("(ReverseProxyServlet) Response headers back to the client:");
        Header[] headerArrayResponse = httpMethodProxyRequest.getResponseHeaders();
        for (Header header : headerArrayResponse) {
            String headerName = header.getName();
            String headerValue = header.getValue();
            if (!headerName.equalsIgnoreCase("Transfer-Encoding")
                    && !headerName.equalsIgnoreCase("Set-Cookie")) {
                httpServletResponse.setHeader(headerName, headerValue);
                Engine.logEngine.debug("   " + headerName + "=" + headerValue);
            }
        }

        String contentType = null;
        Header[] contentTypeHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Type");
        for (Header contentTypeHeader : contentTypeHeaders) {
            contentType = contentTypeHeader.getValue();
            break;
        }

        String pageCharset = "UTF-8";
        if (contentType != null) {
            int iCharset = contentType.indexOf("charset=");
            if (iCharset != -1) {
                pageCharset = contentType.substring(iCharset + "charset=".length()).trim();
            }
            Engine.logEngine.debug("(ReverseProxyServlet) Using charset: " + pageCharset);
        }

        InputStream siteIn = httpMethodProxyRequest.getResponseBodyAsStream();

        // Handle gzipped content
        Header[] contentEncodingHeaders = httpMethodProxyRequest.getResponseHeaders("Content-Encoding");
        boolean bGZip = false, bDeflate = false;
        for (Header contentEncodingHeader : contentEncodingHeaders) {
            HeaderElement[] els = contentEncodingHeader.getElements();
            for (int j = 0; j < els.length; j++) {
                if ("gzip".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode GZip stream");
                    siteIn = new GZIPInputStream(siteIn);
                    bGZip = true;
                } else if ("deflate".equals(els[j].getName())) {
                    Engine.logBeans.debug("(ReverseProxyServlet) Decode Deflate stream");
                    siteIn = new InflaterInputStream(siteIn, new Inflater(true));
                    bDeflate = true;
                }
            }
        }

        byte[] bytesDataResult;

        ByteArrayOutputStream baos = new ByteArrayOutputStream(2048);

        // String resourceUrl = projectName + targetPath;

        String t = context.statistics.start(EngineStatistics.APPLY_USER_REQUEST);

        try {
            // Read either from the cache, either from the remote server
            // InputStream is = proxyCacheManager.getResource(resourceUrl);
            // if (is != null) {
            // Engine.logEngine.debug("(ReverseProxyServlet) Getting data from cache");
            // siteIn = is;
            // }
            int c = siteIn.read();
            while (c > -1) {
                baos.write(c);
                c = siteIn.read();
            }
            // if (is != null) is.close();
        } finally {
            context.statistics.stop(t, true);
        }

        bytesDataResult = baos.toByteArray();
        baos.close();
        Engine.logEngine.debug("(ReverseProxyServlet) Data retrieved!");

        // if (isDynamicContent(httpServletRequest.getPathInfo(),
        // proxyHttpConnector.getDynamicContentFiles())) {
        Engine.logEngine.debug("(ReverseProxyServlet) Dynamic content");

        bytesDataResult = handleStringReplacements(baseUrl, contentType, pageCharset, proxyHttpConnector,
                bytesDataResult);

        String billingClassName = context.getConnector().getBillingClassName();
        if (billingClassName != null) {
            try {
                Engine.logContext.debug("Billing class name required: " + billingClassName);
                AbstractBiller biller = (AbstractBiller) Class.forName(billingClassName).newInstance();
                Engine.logContext.debug("Executing the biller");
                biller.insertBilling(context);
            } catch (Throwable e) {
                Engine.logContext.warn("Unable to execute the biller (the billing is thus ignored): ["
                        + e.getClass().getName() + "] " + e.getMessage());
            }
        }
        // }
        // else {
        // Engine.logEngine.debug("(ReverseProxyServlet) Static content: " +
        // contentType);
        //            
        // // Determine if the resource has already been cached or not
        // CacheEntry cacheEntry =
        // proxyCacheManager.getCacheEntry(resourceUrl);
        // if (cacheEntry instanceof FileCacheEntry) {
        // FileCacheEntry fileCacheEntry = (FileCacheEntry) cacheEntry;
        // File file = new File(fileCacheEntry.fileName);
        // if (!file.exists())
        // proxyCacheManager.removeCacheEntry(cacheEntry);
        // cacheEntry = null;
        // }
        // if (cacheEntry == null) {
        // bytesDataResult = handleStringReplacements(contentType,
        // proxyHttpConnector, bytesDataResult);
        //
        // if (intProxyResponseCode == 200) {
        // Engine.logEngine.debug("(ReverseProxyServlet) Resource stored: "
        // + resourceUrl);
        // cacheEntry = proxyCacheManager.storeResponse(resourceUrl,
        // bytesDataResult);
        // cacheEntry.contentLength = bytesDataResult.length;
        // cacheEntry.contentType = contentType;
        // Engine.logEngine.debug("(ReverseProxyServlet) Cache entry: " +
        // cacheEntry);
        // }
        // }
        // }

        // Send the content to the client
        if (Engine.logEngine.isDebugEnabled() && MimeType.Html.is(contentType)) {
            Engine.logEngine.debug("Data proxied:\n" + new String(bytesDataResult, pageCharset));
        }

        if (bGZip || bDeflate) {
            baos = new ByteArrayOutputStream();
            OutputStream compressedOutputStream = bGZip ? new GZIPOutputStream(baos)
                    : new DeflaterOutputStream(baos,
                            new Deflater(Deflater.DEFAULT_COMPRESSION | Deflater.DEFAULT_STRATEGY, true));
            compressedOutputStream.write(bytesDataResult);
            compressedOutputStream.close();
            bytesDataResult = baos.toByteArray();
            baos.close();
        }

        httpServletResponse.setContentLength(bytesDataResult.length);
        OutputStream outputStreamClientResponse = httpServletResponse.getOutputStream();
        outputStreamClientResponse.write(bytesDataResult);

        Engine.logEngine.debug("(ReverseProxyServlet) End of document retransmission");
    } catch (Exception e) {
        Engine.logEngine.error("Error while trying to proxy page", e);
        throw new ServletException("Error while trying to proxy page", e);
    }
}

From source file:com.liferay.portal.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;
    HttpState httpState = null;/*from w  w  w.  j a  va  2 s.c  om*/

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) | ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if ((cookies != null) && (cookies.length > 0)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            Header contentLength = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLength != null) {
                response.setContentLength(GetterUtil.getInteger(contentLength.getValue()));
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            bytes = FileUtil.getBytes(inputStream);
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:com.twelve.capital.external.feed.util.HttpImpl.java

protected byte[] URLtoByteArray(String location, Http.Method method, Map<String, String> headers,
        Cookie[] cookies, Http.Auth auth, Http.Body body, List<Http.FilePart> fileParts,
        Map<String, String> parts, Http.Response response, boolean followRedirects, String progressId,
        PortletRequest portletRequest) throws IOException {

    byte[] bytes = null;

    HttpMethod httpMethod = null;
    HttpState httpState = null;/*from   w  w w  .j a va  2  s.co m*/

    try {
        _cookies.set(null);

        if (location == null) {
            return null;
        } else if (!location.startsWith(Http.HTTP_WITH_SLASH) && !location.startsWith(Http.HTTPS_WITH_SLASH)) {

            location = Http.HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfiguration = getHostConfiguration(location);

        HttpClient httpClient = getClient(hostConfiguration);

        if (method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) {

            if (method.equals(Http.Method.POST)) {
                httpMethod = new PostMethod(location);
            } else {
                httpMethod = new PutMethod(location);
            }

            if (body != null) {
                RequestEntity requestEntity = new StringRequestEntity(body.getContent(), body.getContentType(),
                        body.getCharset());

                EntityEnclosingMethod entityEnclosingMethod = (EntityEnclosingMethod) httpMethod;

                entityEnclosingMethod.setRequestEntity(requestEntity);
            } else if (method.equals(Http.Method.POST)) {
                PostMethod postMethod = (PostMethod) httpMethod;

                if (!hasRequestHeader(postMethod, HttpHeaders.CONTENT_TYPE)) {

                    HttpClientParams httpClientParams = httpClient.getParams();

                    httpClientParams.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, StringPool.UTF8);
                }

                processPostMethod(postMethod, fileParts, parts);
            }
        } else if (method.equals(Http.Method.DELETE)) {
            httpMethod = new DeleteMethod(location);
        } else if (method.equals(Http.Method.HEAD)) {
            httpMethod = new HeadMethod(location);
        } else {
            httpMethod = new GetMethod(location);
        }

        if (headers != null) {
            for (Map.Entry<String, String> header : headers.entrySet()) {
                httpMethod.addRequestHeader(header.getKey(), header.getValue());
            }
        }

        if ((method.equals(Http.Method.POST) || method.equals(Http.Method.PUT)) && ((body != null)
                || ((fileParts != null) && !fileParts.isEmpty()) || ((parts != null) && !parts.isEmpty()))) {
        } else if (!hasRequestHeader(httpMethod, HttpHeaders.CONTENT_TYPE)) {
            httpMethod.addRequestHeader(HttpHeaders.CONTENT_TYPE,
                    ContentTypes.APPLICATION_X_WWW_FORM_URLENCODED_UTF8);
        }

        if (!hasRequestHeader(httpMethod, HttpHeaders.USER_AGENT)) {
            httpMethod.addRequestHeader(HttpHeaders.USER_AGENT, _DEFAULT_USER_AGENT);
        }

        httpState = new HttpState();

        if (ArrayUtil.isNotEmpty(cookies)) {
            org.apache.commons.httpclient.Cookie[] commonsCookies = toCommonsCookies(cookies);

            httpState.addCookies(commonsCookies);

            HttpMethodParams httpMethodParams = httpMethod.getParams();

            httpMethodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        }

        if (auth != null) {
            httpMethod.setDoAuthentication(true);

            httpState.setCredentials(new AuthScope(auth.getHost(), auth.getPort(), auth.getRealm()),
                    new UsernamePasswordCredentials(auth.getUsername(), auth.getPassword()));
        }

        proxifyState(httpState, hostConfiguration);

        int responseCode = httpClient.executeMethod(hostConfiguration, httpMethod, httpState);

        response.setResponseCode(responseCode);

        Header locationHeader = httpMethod.getResponseHeader("location");

        if ((locationHeader != null) && !locationHeader.equals(location)) {
            String redirect = locationHeader.getValue();

            if (followRedirects) {
                return URLtoByteArray(redirect, Http.Method.GET, headers, cookies, auth, body, fileParts, parts,
                        response, followRedirects, progressId, portletRequest);
            } else {
                response.setRedirect(redirect);
            }
        }

        InputStream inputStream = httpMethod.getResponseBodyAsStream();

        if (inputStream != null) {
            int contentLength = 0;

            Header contentLengthHeader = httpMethod.getResponseHeader(HttpHeaders.CONTENT_LENGTH);

            if (contentLengthHeader != null) {
                contentLength = GetterUtil.getInteger(contentLengthHeader.getValue());

                response.setContentLength(contentLength);
            }

            Header contentType = httpMethod.getResponseHeader(HttpHeaders.CONTENT_TYPE);

            if (contentType != null) {
                response.setContentType(contentType.getValue());
            }

            if (Validator.isNotNull(progressId) && (portletRequest != null)) {

                ProgressInputStream progressInputStream = new ProgressInputStream(portletRequest, inputStream,
                        contentLength, progressId);

                UnsyncByteArrayOutputStream unsyncByteArrayOutputStream = new UnsyncByteArrayOutputStream(
                        contentLength);

                try {
                    progressInputStream.readAll(unsyncByteArrayOutputStream);
                } finally {
                    progressInputStream.clearProgress();
                }

                bytes = unsyncByteArrayOutputStream.unsafeGetByteArray();

                unsyncByteArrayOutputStream.close();
            } else {
                bytes = FileUtil.getBytes(inputStream);
            }
        }

        for (Header header : httpMethod.getResponseHeaders()) {
            response.addHeader(header.getName(), header.getValue());
        }

        return bytes;
    } finally {
        try {
            if (httpState != null) {
                _cookies.set(toServletCookies(httpState.getCookies()));
            }
        } catch (Exception e) {
            _log.error(e, e);
        }

        try {
            if (httpMethod != null) {
                httpMethod.releaseConnection();
            }
        } catch (Exception e) {
            _log.error(e, e);
        }
    }
}

From source file:org.alfresco.jive.impl.JiveOpenClientImpl.java

/**
 * Sets default values for a bunch of standard request headers in the given <code>HttpMethod</code>.
 * Also sets the custom X-AlfrescoJive-UserId header to the encrypted user id.
 * //from w ww .  j  a  v  a 2  s  . c om
 * @param userId The userId to encrypt and add to the header <i>(must not be null, empty or blank)</i>.
 * @param method The method to add the headers to <i>(may be null, in which case this method won't do anything)</i>.
 */
private void setCommonHeaders(final String userId, final HttpMethod method) {
    if (userId == null || userId.trim().length() == 0) {
        throw new AuthenticationException();
    }

    if (method != null) {
        final String encryptedUserId = encrypter.encrypt(userId);

        method.setDoAuthentication(true);
        method.setFollowRedirects(false);
        method.setRequestHeader("Accept", MIME_TYPE_JSON);
        method.setRequestHeader("Accept-Charset", CHARSET_UTF8);
        //            method.setRequestHeader("Accept-Encoding",   "gzip");   // Would dearly love to support compressed responses, but difficult to support in HttpClient 3.1 (used in Alfresco 3.4.x)
        method.setRequestHeader("Connection", "Keep-Alive");
        method.setRequestHeader("Keep-Alive", "300");
        method.setRequestHeader("User-Agent", USER_AGENT);
        method.setRequestHeader(HEADER_NAME_USER_ID, encryptedUserId);
    }
}