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

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

Introduction

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

Prototype

public void setHost(URI paramURI) 

Source Link

Usage

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

@Override
protected void writeResponseResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = GetBuildStatus.getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {/*  w ww .  j av  a 2 s. c om*/
        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!");
        }
    }

    String platformName = Keys.platform.value(request);
    String finalApplicationName = mobileApplication.getComputedApplicationName();

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    PostMethod method;
    int methodStatusCode;
    InputStream methodBodyContentInputStream;

    URL url = new URL(mobileBuilderPlatformURL + "/getpackage");

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

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

    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] { new NameValuePair("application", finalApplicationName),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);
        methodBodyContentInputStream = method.getResponseBodyAsStream();

        if (methodStatusCode != HttpStatus.SC_OK) {
            byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
            String sResult = new String(httpBytes, "UTF-8");
            throw new ServiceException("Unable to get package for project '" + project + "' (final app name: '"
                    + finalApplicationName + "').\n" + sResult);
        }

        try {
            String contentDisposition = method.getResponseHeader(HeaderName.ContentDisposition.value())
                    .getValue();
            HeaderName.ContentDisposition.setHeader(response, contentDisposition);
        } catch (Exception e) {
            HeaderName.ContentDisposition.setHeader(response, "attachment; filename=\"" + project + "\"");
        }

        try {
            response.setContentType(method.getResponseHeader(HeaderName.ContentType.value()).getValue());
        } catch (Exception e) {
            response.setContentType(MimeType.OctetStream.value());
        }

        OutputStream responseOutputStream = response.getOutputStream();
        IOUtils.copy(methodBodyContentInputStream, responseOutputStream);
    } catch (IOException ioex) { // Fix for ticket #4698
        if (!ioex.getClass().getSimpleName().equalsIgnoreCase("ClientAbortException")) {
            // fix for #5042
            throw ioex;
        }
    } finally {
        method.releaseConnection();
    }
}

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

@Override
protected void getServiceResult(HttpServletRequest request, Document document) throws Exception {
    String project = Keys.project.value(request);

    MobileApplication mobileApplication = getMobileApplication(project);

    if (mobileApplication == null) {
        throw new ServiceException("no such mobile application");
    } else {//from  w w w  . jav  a  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!");
        }
    }

    String platformName = Keys.platform.value(request);

    String mobileBuilderPlatformURL = EnginePropertiesManager
            .getProperty(PropertyName.MOBILE_BUILDER_PLATFORM_URL);

    URL url = new URL(mobileBuilderPlatformURL + "/getstatus");

    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());

    JSONObject jsonResult;
    try {
        HeaderName.ContentType.setRequestHeader(method, MimeType.WwwForm.value());
        method.setRequestBody(new NameValuePair[] {
                new NameValuePair("application", mobileApplication.getComputedApplicationName()),
                new NameValuePair("platformName", platformName),
                new NameValuePair("auth_token", mobileApplication.getComputedAuthenticationToken()),
                new NameValuePair("endpoint", mobileApplication.getComputedEndpoint(request)) });

        int methodStatusCode = Engine.theApp.httpClient.executeMethod(hostConfiguration, method, httpState);

        InputStream methodBodyContentInputStream = method.getResponseBodyAsStream();
        byte[] httpBytes = IOUtils.toByteArray(methodBodyContentInputStream);
        String sResult = new String(httpBytes, "UTF-8");

        if (methodStatusCode != HttpStatus.SC_OK) {
            throw new ServiceException(
                    "Unable to get building status for application '" + project + "' (final app name: '"
                            + mobileApplication.getComputedApplicationName() + "').\n" + sResult);
        }

        jsonResult = new JSONObject(sResult);
    } finally {
        method.releaseConnection();
    }

    Element statusElement = document.createElement("build");
    statusElement.setAttribute(Keys.project.name(), project);
    statusElement.setAttribute(Keys.platform.name(), platformName);

    if (jsonResult.has(platformName + "_status")) {
        statusElement.setAttribute("status", jsonResult.getString(platformName + "_status"));
    } else {
        statusElement.setAttribute("status", "none");
    }

    if (jsonResult.has(platformName + "_error")) {
        statusElement.setAttribute("error", jsonResult.getString(platformName + "_error"));
    }

    statusElement.setAttribute("version", jsonResult.has("version") ? jsonResult.getString("version") : "n/a");
    statusElement.setAttribute("phonegap_version",
            jsonResult.has("phonegap_version") ? jsonResult.getString("phonegap_version") : "n/a");

    statusElement.setAttribute("revision",
            jsonResult.has("revision") ? jsonResult.getString("revision") : "n/a");
    statusElement.setAttribute("endpoint",
            jsonResult.has("endpoint") ? jsonResult.getString("endpoint") : "n/a");

    document.getDocumentElement().appendChild(statusElement);
}

From source file:com.silverpeas.openoffice.windows.webdav.WebdavManager.java

/**
 * Prepare HTTP connections to the WebDav server
 *
 * @param host the webdav server host name.
 * @param login the login for the user on the webdav server.
 * @param password the login for the user on the webdav server.
 *//*from   ww  w .j  a  v a  2s .c  om*/
public WebdavManager(String host, String login, String password) {
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(host);
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams connectionParams = new HttpConnectionManagerParams();
    int maxHostConnections = 20;
    connectionParams.setMaxConnectionsPerHost(hostConfig, maxHostConnections);
    connectionManager.setParams(connectionParams);
    HttpClientParams clientParams = new HttpClientParams();
    clientParams.setParameter(HttpClientParams.CREDENTIAL_CHARSET, "UTF-8");
    clientParams.setParameter(HttpClientParams.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
    client = new HttpClient(clientParams, connectionManager);
    Credentials creds = new UsernamePasswordCredentials(login, password);
    client.getState().setCredentials(AuthScope.ANY, creds);
    client.setHostConfiguration(hostConfig);
}

From source file:com.trendmicro.hdfs.webdav.test.MiniClusterTestUtil.java

public HttpClient getClient() {
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost("localhost");
    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();
    params.setMaxConnectionsPerHost(hostConfig, 100);
    connectionManager.setParams(params);
    HttpClient client = new HttpClient(connectionManager);
    client.setHostConfiguration(hostConfig);
    return client;
}

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 {/*from  www .  ja v  a  2 s. co  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:de.kp.ames.webdav.WebDAVClient.java

/**
 * Constructor// w ww .  ja  v  a2  s.c  o  m
 * 
 * @param alias
 * @param keypass
 * @param uri
 */
public WebDAVClient(String alias, String keypass, String uri) {

    /*
     * Register request uri
     */
    this.uri = uri;

    /*
     * Setup HttpClient
     */
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(uri);

    HttpConnectionManager connectionManager = new MultiThreadedHttpConnectionManager();
    HttpConnectionManagerParams params = new HttpConnectionManagerParams();

    int maxHostConnections = 200;
    params.setMaxConnectionsPerHost(hostConfig, maxHostConnections);

    connectionManager.setParams(params);

    client = new HttpClient(connectionManager);
    client.setHostConfiguration(hostConfig);

    Credentials creds = new UsernamePasswordCredentials(alias, keypass);
    client.getState().setCredentials(AuthScope.ANY, creds);

}

From source file:com.noelios.restlet.ext.httpclient.HttpMethodCall.java

/**
 * Constructor./*  w ww  . jav a  2s . c om*/
 * 
 * @param helper
 *            The parent HTTP client helper.
 * @param method
 *            The method name.
 * @param requestUri
 *            The request URI.
 * @param hasEntity
 *            Indicates if the call will have an entity to send to the
 *            server.
 * @throws IOException
 */
public HttpMethodCall(HttpClientHelper helper, final String method, String requestUri, boolean hasEntity)
        throws IOException {
    super(helper, method, requestUri);
    this.clientHelper = helper;

    if (requestUri.startsWith("http")) {
        if (method.equalsIgnoreCase(Method.GET.getName())) {
            this.httpMethod = new GetMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.POST.getName())) {
            this.httpMethod = new PostMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.PUT.getName())) {
            this.httpMethod = new PutMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.HEAD.getName())) {
            this.httpMethod = new HeadMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.DELETE.getName())) {
            this.httpMethod = new DeleteMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.CONNECT.getName())) {
            final HostConfiguration host = new HostConfiguration();
            host.setHost(new URI(requestUri, false));
            this.httpMethod = new ConnectMethod(host);
        } else if (method.equalsIgnoreCase(Method.OPTIONS.getName())) {
            this.httpMethod = new OptionsMethod(requestUri);
        } else if (method.equalsIgnoreCase(Method.TRACE.getName())) {
            this.httpMethod = new TraceMethod(requestUri);
        } else {
            this.httpMethod = new EntityEnclosingMethod(requestUri) {
                @Override
                public String getName() {
                    return method;
                }
            };
        }

        this.httpMethod.setFollowRedirects(this.clientHelper.isFollowRedirects());
        this.httpMethod.setDoAuthentication(false);

        if (this.clientHelper.getRetryHandler() != null) {
            try {
                this.httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                        Engine.loadClass(this.clientHelper.getRetryHandler()).newInstance());
            } catch (Exception e) {
                this.clientHelper.getLogger().log(Level.WARNING,
                        "An error occurred during the instantiation of the retry handler.", e);
            }
        }

        this.responseHeadersAdded = false;
        setConfidential(this.httpMethod.getURI().getScheme().equalsIgnoreCase(Protocol.HTTPS.getSchemeName()));
    } else {
        throw new IllegalArgumentException("Only HTTP or HTTPS resource URIs are allowed here");
    }
}

From source file:davmail.util.ClientCertificateTest.java

@Override
public void setUp() throws IOException {
    if (httpClient == null) {
        System.setProperty("javax.net.ssl.trustStore", "cacerts");
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
        System.setProperty("javax.net.debug", "ssl,handshake");

        httpClient = new HttpClient();
        HostConfiguration hostConfig = httpClient.getHostConfiguration();
        URI httpURI = new URI("https://localhost", true);
        hostConfig.setHost(httpURI);

        Protocol.registerProtocol("https",
                new Protocol("https", (ProtocolSocketFactory) new DavGatewaySSLProtocolSocketFactory(), 443));
    }/*from w  w  w  .j  a  v a2 s .co m*/
}

From source file:com.springsource.insight.plugin.apache.http.hc3.HttpClientExecutionCollectionAspectTest.java

private void runExecuteHostMethodTest(String testName, HttpState state) throws Exception {
    HttpHost host = new HttpHost("localhost", TEST_PORT);
    HostConfiguration hostConfig = new HostConfiguration();
    hostConfig.setHost(host);
    runExecuteMethodTest(testName, hostConfig, state);
}

From source file:davmail.caldav.TestCaldav.java

@Override
public void setUp() throws IOException {
    super.setUp();
    if (httpClient == null) {
        // start gateway
        DavGateway.start();//from w  w w .j a  v a 2s .  c  o m
        httpClient = new HttpClient();
        HostConfiguration hostConfig = httpClient.getHostConfiguration();
        URI httpURI = new URI("http://localhost:" + Settings.getProperty("davmail.caldavPort"), true);
        hostConfig.setHost(httpURI);
        AuthScope authScope = new AuthScope(null, -1);
        httpClient.getState().setCredentials(authScope, new NTCredentials(
                Settings.getProperty("davmail.username"), Settings.getProperty("davmail.password"), "", ""));
    }
    if (session == null) {
        session = ExchangeSessionFactory.getInstance(Settings.getProperty("davmail.username"),
                Settings.getProperty("davmail.password"));
    }
}