Example usage for org.apache.commons.httpclient HostConfiguration HostConfiguration

List of usage examples for org.apache.commons.httpclient HostConfiguration HostConfiguration

Introduction

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

Prototype

public HostConfiguration() 

Source Link

Usage

From source file:io.hops.hopsworks.api.admin.YarnUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//from   ww  w.j a  v a2  s  . c  o  m
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        // Execute the request

        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        String method = servletRequest.getMethod();
        HttpMethod m;
        if (method.equalsIgnoreCase("PUT")) {
            m = new PutMethod(proxyRequestUri);
            RequestEntity requestEntity = new InputStreamRequestEntity(servletRequest.getInputStream(),
                    servletRequest.getContentType());
            ((PutMethod) m).setRequestEntity(requestEntity);
        } else {
            m = new GetMethod(proxyRequestUri);
        }
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //yarn does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:com.eviware.soapui.impl.wsdl.monitor.jettyproxy.ProxyServlet.java

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException {
    monitor.fireOnRequest(request, response);
    if (response.isCommitted())
        return;/*from   w  ww  . j  a v a 2 s .  c o  m*/

    ExtendedHttpMethod method;
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if (httpRequest.getMethod().equals("GET"))
        method = new ExtendedGetMethod();
    else
        method = new ExtendedPostMethod();

    method.setDecompress(false);

    // for this create ui server and port, properties.
    JProxyServletWsdlMonitorMessageExchange capturedData = new JProxyServletWsdlMonitorMessageExchange(project);
    capturedData.setRequestHost(httpRequest.getServerName());
    capturedData.setRequestMethod(httpRequest.getMethod());
    capturedData.setRequestHeader(httpRequest);
    capturedData.setHttpRequestParameters(httpRequest);
    capturedData.setTargetURL(httpRequest.getRequestURL().toString());

    CaptureInputStream capture = new CaptureInputStream(httpRequest.getInputStream());

    // check connection header
    String connectionHeader = httpRequest.getHeader("Connection");
    if (connectionHeader != null) {
        connectionHeader = connectionHeader.toLowerCase();
        if (connectionHeader.indexOf("keep-alive") < 0 && connectionHeader.indexOf("close") < 0)
            connectionHeader = null;
    }

    // copy headers
    boolean xForwardedFor = false;
    @SuppressWarnings("unused")
    long contentLength = -1;
    Enumeration<?> headerNames = httpRequest.getHeaderNames();
    while (headerNames.hasMoreElements()) {
        String hdr = (String) headerNames.nextElement();
        String lhdr = hdr.toLowerCase();

        if (dontProxyHeaders.contains(lhdr))
            continue;
        if (connectionHeader != null && connectionHeader.indexOf(lhdr) >= 0)
            continue;

        if ("content-length".equals(lhdr))
            contentLength = request.getContentLength();

        Enumeration<?> vals = httpRequest.getHeaders(hdr);
        while (vals.hasMoreElements()) {
            String val = (String) vals.nextElement();
            if (val != null) {
                method.setRequestHeader(lhdr, val);
                xForwardedFor |= "X-Forwarded-For".equalsIgnoreCase(hdr);
            }
        }
    }

    // Proxy headers
    method.setRequestHeader("Via", "SoapUI Monitor");
    if (!xForwardedFor)
        method.addRequestHeader("X-Forwarded-For", request.getRemoteAddr());

    if (method instanceof ExtendedPostMethod)
        ((ExtendedPostMethod) method)
                .setRequestEntity(new InputStreamRequestEntity(capture, request.getContentType()));

    HostConfiguration hostConfiguration = new HostConfiguration();

    StringBuffer url = new StringBuffer("http://");
    url.append(httpRequest.getServerName());
    if (httpRequest.getServerPort() != 80)
        url.append(":" + httpRequest.getServerPort());
    if (httpRequest.getServletPath() != null) {
        url.append(httpRequest.getServletPath());
        method.setPath(httpRequest.getServletPath());
        if (httpRequest.getQueryString() != null) {
            url.append("?" + httpRequest.getQueryString());
            method.setPath(httpRequest.getServletPath() + "?" + httpRequest.getQueryString());
        }
    }
    hostConfiguration.setHost(new URI(url.toString(), true));

    // SoapUI.log("PROXY to:" + url);

    monitor.fireBeforeProxy(request, response, method, hostConfiguration);

    if (settings.getBoolean(LaunchForm.SSLTUNNEL_REUSESTATE)) {
        if (httpState == null)
            httpState = new HttpState();
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method, httpState);
    } else {
        HttpClientSupport.getHttpClient().executeMethod(hostConfiguration, method);
    }

    // wait for transaction to end and store it.
    capturedData.stopCapture();

    capturedData.setRequest(capture.getCapturedData());
    capturedData.setRawResponseBody(method.getResponseBody());
    capturedData.setResponseHeader(method);
    capturedData.setRawRequestData(getRequestToBytes(request.toString(), method, capture));
    capturedData.setRawResponseData(
            getResponseToBytes(response.toString(), method, capturedData.getRawResponseBody()));
    capturedData.setResponseContent(new String(method.getDecompressedResponseBody()));

    monitor.fireAfterProxy(request, response, method, capturedData);

    if (!response.isCommitted()) {
        StringToStringsMap responseHeaders = capturedData.getResponseHeaders();
        // capturedData = null;

        // copy headers to response
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        for (String name : responseHeaders.keySet()) {
            for (String header : responseHeaders.get(name))
                httpResponse.addHeader(name, header);
        }

        IO.copy(new ByteArrayInputStream(capturedData.getRawResponseBody()), httpResponse.getOutputStream());
    }

    synchronized (this) {
        if (checkContentType(method)) {
            monitor.addMessageExchange(capturedData);
        }
    }
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClientTest.java

@Test(expectedExceptions = HttpClientException.class)
public void testPostJsonBytesThrowsException() throws Exception {
    ApacheHttpClient31BackedHttpClient client = new ApacheHttpClient31BackedHttpClient(httpClient,
            new HashMap<String, String>());

    final String path = "/path/to/endpoint";

    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost("foobar.com", 3456, Protocol.getProtocol("http"));
    when(httpClient.getHostConfiguration()).thenReturn(hostConfiguration);
    when(httpClient.executeMethod(Matchers.<HttpMethod>any())).thenThrow(new IOException());

    client.postBytes(path, "body".getBytes("UTF-8"));
}

From source file:com.twinsoft.convertigo.engine.admin.services.mobiles.LaunchBuild.java

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    synchronized (buildLock) {
        final MobileResourceHelper mobileResourceHelper = new MobileResourceHelper(request, "mobile/www");
        MobileApplication mobileApplication = mobileResourceHelper.mobileApplication;

        if (mobileApplication == null) {
            throw new ServiceException("no such mobile application");
        } else {/* w  w w .  ja  va 2  s .  c  o m*/
            boolean bAdminRole = Engine.authenticatedSessionManager.hasRole(request.getSession(),
                    Role.WEB_ADMIN);
            if (!bAdminRole && mobileApplication.getAccessibility() == Accessibility.Private) {
                throw new AuthenticationException("Authentication failure: user has not sufficient rights!");
            }
        }

        MobilePlatform mobilePlatform = mobileResourceHelper.mobilePlatform;

        String finalApplicationName = mobileApplication.getComputedApplicationName();
        File mobileArchiveFile = mobileResourceHelper.makeZipPackage();

        // Login to the mobile builder platform
        String mobileBuilderPlatformURL = EnginePropertiesManager
                .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

        Map<String, String[]> params = new HashMap<String, String[]>();

        params.put("application", new String[] { finalApplicationName });
        params.put("platformName", new String[] { mobilePlatform.getName() });
        params.put("platformType", new String[] { mobilePlatform.getType() });
        params.put("auth_token", new String[] { mobileApplication.getComputedAuthenticationToken() });

        //revision and endpoint params
        params.put("revision", new String[] { mobileResourceHelper.getRevision() });
        params.put("endpoint", new String[] { mobileApplication.getComputedEndpoint(request) });

        //iOS
        if (mobilePlatform instanceof IOs) {
            IOs ios = (IOs) mobilePlatform;

            String pw, title = ios.getiOSCertificateTitle();

            if (!title.equals("")) {
                pw = ios.getiOSCertificatePw();
            } else {
                title = EnginePropertiesManager.getProperty(PropertyName.MOBILE_BUILDER_IOS_CERTIFICATE_TITLE);
                pw = EnginePropertiesManager.getProperty(PropertyName.MOBILE_BUILDER_IOS_CERTIFICATE_PW);
            }

            params.put("iOSCertificateTitle", new String[] { title });
            params.put("iOSCertificatePw", new String[] { pw });
        }

        //Android
        if (mobilePlatform instanceof Android) {
            Android android = (Android) mobilePlatform;

            String certificatePw, keystorePw, title = android.getAndroidCertificateTitle();

            if (!title.equals("")) {
                certificatePw = android.getAndroidCertificatePw();
                keystorePw = android.getAndroidKeystorePw();
            } else {
                title = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_ANDROID_CERTIFICATE_TITLE);
                certificatePw = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_ANDROID_CERTIFICATE_PW);
                keystorePw = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_ANDROID_KEYSTORE_PW);
            }

            params.put("androidCertificateTitle", new String[] { title });
            params.put("androidCertificatePw", new String[] { certificatePw });
            params.put("androidKeystorePw", new String[] { keystorePw });
        }

        //Windows Phone
        if (mobilePlatform instanceof WindowsPhoneKeyProvider) {
            WindowsPhoneKeyProvider windowsPhone = (WindowsPhoneKeyProvider) mobilePlatform;

            String title = windowsPhone.getWinphonePublisherIdTitle();

            if (title.equals("")) {
                title = EnginePropertiesManager
                        .getProperty(PropertyName.MOBILE_BUILDER_WINDOWSPHONE_PUBLISHER_ID_TITLE);
            }

            params.put("winphonePublisherIdTitle", new String[] { title });
        }

        // Launch the mobile build
        URL url = new URL(mobileBuilderPlatformURL + "/build?" + URLUtils.mapToQuery(params));

        HostConfiguration hostConfiguration = new HostConfiguration();
        hostConfiguration.setHost(url.getHost());
        HttpState httpState = new HttpState();
        Engine.theApp.proxyManager.setProxy(hostConfiguration, httpState, url);

        PostMethod method = new PostMethod(url.toString());

        FileRequestEntity entity = new FileRequestEntity(mobileArchiveFile, null);
        method.setRequestEntity(entity);

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        String sResult = IOUtils.toString(method.getResponseBodyAsStream(), "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to build application '" + finalApplicationName + "'.\n" + sResult);
        }

        JSONObject jsonObject = new JSONObject(sResult);
        Element statusElement = document.createElement("application");
        statusElement.setAttribute("id", jsonObject.getString("id"));
        document.getDocumentElement().appendChild(statusElement);
    }
}

From source file:com.liferay.util.Http.java

public static byte[] URLtoByteArray(String location, Cookie[] cookies, boolean post) throws IOException {

    byte[] byteArray = null;

    HttpMethod method = null;/*from w w w  .  j  av  a 2  s  .co m*/

    try {
        HttpClient client = new HttpClient(new SimpleHttpConnectionManager());

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

            location = HTTP_WITH_SLASH + location;
        }

        HostConfiguration hostConfig = new HostConfiguration();

        hostConfig.setHost(new URI(location));

        if (Validator.isNotNull(PROXY_HOST) && PROXY_PORT > 0) {
            hostConfig.setProxy(PROXY_HOST, PROXY_PORT);
        }

        client.setHostConfiguration(hostConfig);
        client.setConnectionTimeout(5000);
        client.setTimeout(5000);

        if (cookies != null && cookies.length > 0) {
            HttpState state = new HttpState();

            state.addCookies(cookies);
            state.setCookiePolicy(CookiePolicy.COMPATIBILITY);

            client.setState(state);
        }

        if (post) {
            method = new PostMethod(location);
        } else {
            method = new GetMethod(location);
        }

        method.setFollowRedirects(true);

        client.executeMethod(method);

        Header locationHeader = method.getResponseHeader("location");
        if (locationHeader != null) {
            return URLtoByteArray(locationHeader.getValue(), cookies, post);
        }

        InputStream is = method.getResponseBodyAsStream();

        if (is != null) {
            ByteArrayOutputStream buffer = new ByteArrayOutputStream();
            byte[] bytes = new byte[512];

            for (int i = is.read(bytes, 0, 512); i != -1; i = is.read(bytes, 0, 512)) {

                buffer.write(bytes, 0, i);
            }

            byteArray = buffer.toByteArray();

            is.close();
            buffer.close();
        }

        return byteArray;
    } finally {
        try {
            if (method != null) {
                method.releaseConnection();
            }
        } catch (Exception e) {
            Logger.error(Http.class, e.getMessage(), e);
        }
    }
}

From source file:com.orange.mmp.net.http.HttpConnection.java

/**
 * Inner method used to execute request/*w  ww . j a  v a  2s  .  c om*/
 * 
 * @param dataStream The data stream to send in request (null for GET only)
 * @throws MMPNetException 
 */
@SuppressWarnings("unchecked")
protected void doExecute(InputStream dataStream) throws MMPNetException {
    try {
        this.currentHttpClient = HttpConnectionManager.httpClientPool.take();
    } catch (InterruptedException ie) {
        throw new MMPNetException("Corrupted HTTP client pool", ie);
    }

    if (this.httpConnectionProperties.containsKey(HttpConnectionParameters.PARAM_IN_CREDENTIALS_USER)) {
        this.currentHttpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                (String) this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_CREDENTIALS_USER),
                (String) this.httpConnectionProperties
                        .get(HttpConnectionParameters.PARAM_IN_CREDENTIALS_PASSWORD)));
        this.currentHttpClient.getParams().setAuthenticationPreemptive(true);
    }

    // Config
    HostConfiguration config = new HostConfiguration();
    if (this.timeout > 0)
        this.currentHttpClient.getParams().setParameter(HttpConnectionParameters.PARAM_IN_HTTP_SOCKET_TIMEOUT,
                this.timeout);
    if (HttpConnectionManager.proxyHost != null
            && (this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) != null
                    && this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY)
                            .toString().equals("true"))
            || (this.httpConnectionProperties.get(HttpConnectionParameters.PARAM_IN_HTTP_USE_PROXY) == null
                    && this.useProxy)) {
        config.setProxy(HttpConnectionManager.proxyHost, HttpConnectionManager.proxyPort);
    } else {
        config.setProxyHost(null);
    }
    this.currentHttpClient.setHostConfiguration(config);
    this.currentHttpClient.getHostConfiguration().setHost(new HttpHost(this.endPointUrl.getHost()));

    String methodStr = (String) this.httpConnectionProperties
            .get(HttpConnectionParameters.PARAM_IN_HTTP_METHOD);

    if (methodStr == null || methodStr.equals(HttpConnectionParameters.HTTP_METHOD_GET)) {
        this.method = new GetMethod(endPointUrl.toString().replace(" ", "+"));
    } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_POST)) {
        this.method = new PostMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath()
                : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery());
        if (dataStream != null) {
            InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(dataStream);
            ((PostMethod) this.method).setRequestEntity(inputStreamRequestEntity);
        }
    } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_PUT)) {
        this.method = new PutMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath()
                : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery());
        if (dataStream != null) {
            InputStreamRequestEntity inputStreamRequestEntity = new InputStreamRequestEntity(dataStream);
            ((PutMethod) this.method).setRequestEntity(inputStreamRequestEntity);
        }
    } else if (methodStr.equals(HttpConnectionParameters.HTTP_METHOD_DEL)) {
        this.method = new DeleteMethod((this.endPointUrl.getQuery() == null) ? this.endPointUrl.getPath()
                : this.endPointUrl.getPath() + "?" + endPointUrl.getQuery());
    } else
        throw new MMPNetException("HTTP method not supported");

    //Add headers
    if (this.httpConnectionProperties != null) {
        for (Object headerName : this.httpConnectionProperties.keySet()) {
            if (!((String) headerName).startsWith("http.")) {
                this.method.addRequestHeader((String) headerName,
                        this.httpConnectionProperties.get(headerName).toString());
            }
        }
    }
    // Set Connection/Proxy-Connection close to avoid TIME_WAIT sockets
    this.method.addRequestHeader("Connection", "close");
    this.method.addRequestHeader("Proxy-Connection", "close");

    try {
        int httpCode = this.currentHttpClient.executeMethod(config, method);
        this.currentStatusCode = httpCode;

        for (org.apache.commons.httpclient.Header responseHeader : method.getResponseHeaders()) {
            this.httpConnectionProperties.put(responseHeader.getName(), responseHeader.getValue());
        }

        if (this.currentStatusCode >= 400) {
            throw new MMPNetException("HTTP " + this.currentStatusCode + " on '" + endPointUrl + "'");
        } else {
            this.inDataStream = this.method.getResponseBodyAsStream();
        }
    } catch (IOException ioe) {
        throw new MMPNetException("I/O error on " + this.endPointUrl + " : " + ioe.getMessage());
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.taobao.diamond.client.impl.DefaultDiamondSubscriber.java

protected void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;//from ww  w.  j  a  v  a2 s . c om
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
            diamondConfigure.getPort());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    // 1,
    // boyan@taobao.com
    params.setSoTimeout(60 * 1000);

    connectionManager.setParams(params);
    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}

From source file:cn.leancloud.diamond.client.impl.DefaultDiamondSubscriber.java

protected void initHttpClient() {
    if (MockServer.isTestMode()) {
        return;//from   w  w w.java 2  s . co m
    }
    HostConfiguration hostConfiguration = new HostConfiguration();
    hostConfiguration.setHost(diamondConfigure.getDomainNameList().get(this.domainNamePos.get()),
            diamondConfigure.getPort());

    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.closeIdleConnections(diamondConfigure.getPollingIntervalTime() * 4000);

    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setStaleCheckingEnabled(diamondConfigure.isConnectionStaleCheckingEnabled());
    params.setMaxConnectionsPerHost(hostConfiguration, diamondConfigure.getMaxHostConnections());
    params.setMaxTotalConnections(diamondConfigure.getMaxTotalConnections());
    params.setConnectionTimeout(diamondConfigure.getConnectionTimeout());
    // 1,
    // boyan@taobao.com
    params.setSoTimeout(60 * 1000);

    connectionManager.setParams(params);
    httpClient = new HttpClient(connectionManager);
    httpClient.setHostConfiguration(hostConfiguration);
}

From source file:io.hops.hopsworks.api.admin.HDFSUIProxyServlet.java

@Override
protected void service(HttpServletRequest servletRequest, HttpServletResponse servletResponse)
        throws ServletException, IOException {

    if (servletRequest.getUserPrincipal() == null) {
        servletResponse.sendError(403, "User is not logged in");
        return;//from ww  w .  jav  a  2s  .  c  om
    }
    if (!servletRequest.isUserInRole("HOPS_ADMIN")) {
        servletResponse.sendError(Response.Status.BAD_REQUEST.getStatusCode(),
                "You don't have the access right for this service");
        return;
    }
    if (servletRequest.getAttribute(ATTR_TARGET_URI) == null) {
        servletRequest.setAttribute(ATTR_TARGET_URI, targetUri);
    }
    if (servletRequest.getAttribute(ATTR_TARGET_HOST) == null) {
        servletRequest.setAttribute(ATTR_TARGET_HOST, targetHost);
    }

    // Make the Request
    // note: we won't transfer the protocol version because I'm not 
    // sure it would truly be compatible
    String proxyRequestUri = rewriteUrlFromRequest(servletRequest);

    try {
        String[] targetHost_port = settings.getHDFSWebUIAddress().split(":");
        File keyStore = new File(baseHadoopClientsService.getSuperKeystorePath());
        File trustStore = new File(baseHadoopClientsService.getSuperTrustStorePath());
        // Assume that KeyStore password and Key password are the same
        Protocol httpsProto = new Protocol("https",
                new CustomSSLProtocolSocketFactory(keyStore,
                        baseHadoopClientsService.getSuperKeystorePassword(),
                        baseHadoopClientsService.getSuperKeystorePassword(), trustStore,
                        baseHadoopClientsService.getSuperTrustStorePassword()),
                Integer.parseInt(targetHost_port[1]));
        Protocol.registerProtocol("https", httpsProto);
        // Execute the request
        HttpClientParams params = new HttpClientParams();
        params.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        params.setBooleanParameter(HttpClientParams.ALLOW_CIRCULAR_REDIRECTS, true);
        HttpClient client = new HttpClient(params);
        HostConfiguration config = new HostConfiguration();
        InetAddress localAddress = InetAddress.getLocalHost();
        config.setLocalAddress(localAddress);

        HttpMethod m = new GetMethod(proxyRequestUri);
        Enumeration<String> names = servletRequest.getHeaderNames();
        while (names.hasMoreElements()) {
            String headerName = names.nextElement();
            String value = servletRequest.getHeader(headerName);
            if (PASS_THROUGH_HEADERS.contains(headerName)) {
                //hdfs does not send back the js if encoding is not accepted
                //but we don't want to accept encoding for the html because we
                //need to be able to parse it
                if (headerName.equalsIgnoreCase("accept-encoding") && (servletRequest.getPathInfo() == null
                        || !servletRequest.getPathInfo().contains(".js"))) {
                    continue;
                } else {
                    m.setRequestHeader(headerName, value);
                }
            }
        }
        String user = servletRequest.getRemoteUser();
        if (user != null && !user.isEmpty()) {
            m.setRequestHeader("Cookie", "proxy-user" + "=" + URLEncoder.encode(user, "ASCII"));
        }

        client.executeMethod(config, m);

        // Process the response
        int statusCode = m.getStatusCode();

        // Pass the response code. This method with the "reason phrase" is 
        //deprecated but it's the only way to pass the reason along too.
        //noinspection deprecation
        servletResponse.setStatus(statusCode, m.getStatusLine().getReasonPhrase());

        copyResponseHeaders(m, servletRequest, servletResponse);

        // Send the content to the client
        copyResponseEntity(m, servletResponse);

    } catch (Exception e) {
        if (e instanceof RuntimeException) {
            throw (RuntimeException) e;
        }
        if (e instanceof ServletException) {
            throw (ServletException) e;
        }
        //noinspection ConstantConditions
        if (e instanceof IOException) {
            throw (IOException) e;
        }
        throw new RuntimeException(e);

    }
}

From source file:ac.elements.io.Signature.java

/**
 * Configure HttpClient with set of defaults as well as configuration from
 * AmazonEC2Config instance./*from   w w  w  .  j  a  v a 2s .co m*/
 * 
 * @return the http client
 */
private static HttpClient configureHttpClient() {

    /* Set http client parameters */
    HttpClientParams httpClientParams = new HttpClientParams();
    httpClientParams.setParameter(HttpMethodParams.USER_AGENT, USER_AGENT);
    httpClientParams.setParameter(HttpMethodParams.RETRY_HANDLER, new HttpMethodRetryHandler() {

        public boolean retryMethod(HttpMethod method, IOException exception, int executionCount) {
            if (executionCount > MAX_RETRY_ERROR) {
                log.warn("Maximum Number of Retry attempts " + "reached, will not retry");
                return false;
            }
            log.warn("Retrying request. Attempt " + executionCount);
            if (exception instanceof NoHttpResponseException) {
                log.warn("Retrying on NoHttpResponseException");
                return true;
            }
            if (exception instanceof InterruptedIOException) {
                log.warn("Will not retry on InterruptedIOException", exception);
                return false;
            }
            if (exception instanceof UnknownHostException) {
                log.warn("Will not retry on UnknownHostException", exception);
                return false;
            }
            if (!method.isRequestSent()) {
                log.warn("Retrying on failed sent request");
                return true;
            }
            return false;
        }
    });

    /* Set host configuration */
    HostConfiguration hostConfiguration = new HostConfiguration();

    /* Set connection manager parameters */
    HttpConnectionManagerParams connectionManagerParams = new HttpConnectionManagerParams();
    connectionManagerParams.setConnectionTimeout(50000);
    connectionManagerParams.setSoTimeout(50000);
    connectionManagerParams.setStaleCheckingEnabled(true);
    connectionManagerParams.setTcpNoDelay(true);
    connectionManagerParams.setMaxTotalConnections(MAX_CONNECTIONS);
    connectionManagerParams.setMaxConnectionsPerHost(hostConfiguration, MAX_CONNECTIONS);

    /* Set connection manager */
    MultiThreadedHttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    connectionManager.setParams(connectionManagerParams);

    /* Set http client */
    httpClient = new HttpClient(httpClientParams, connectionManager);

    /* Set proxy if configured */
    // if (config.isSetProxyHost() && config.isSetProxyPort()) {
    // log.info("Configuring Proxy. Proxy Host: " + config.getProxyHost() +
    // "Proxy Port: " + config.getProxyPort() );
    // hostConfiguration.setProxy(config.getProxyHost(),
    // config.getProxyPort());
    // if (config.isSetProxyUsername() && config.isSetProxyPassword()) {
    // httpClient.getState().setProxyCredentials (new AuthScope(
    // config.getProxyHost(),
    // config.getProxyPort()),
    // new UsernamePasswordCredentials(
    // config.getProxyUsername(),
    // config.getProxyPassword()));
    //        
    // }
    // }
    httpClient.setHostConfiguration(hostConfiguration);
    return httpClient;
}