Example usage for org.apache.commons.httpclient HttpClient getHost

List of usage examples for org.apache.commons.httpclient HttpClient getHost

Introduction

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

Prototype

public String getHost() 

Source Link

Usage

From source file:com.cloud.utils.net.HTTPUtils.java

/**
 * @param username/*from  ww w  . j ava 2s .co m*/
 * @param password
 * @param httpClient
 */
public static void setCredentials(String username, String password, HttpClient httpClient) {
    if (username != null && password != null && httpClient != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Setting credentials with username " + username + " for host "
                    + httpClient.getHostConfiguration().getHost() + ":"
                    + httpClient.getHostConfiguration().getPort());
        }

        httpClient.getParams().setAuthenticationPreemptive(true);
        httpClient.getState().setCredentials(
                new AuthScope(httpClient.getHostConfiguration().getHost(),
                        httpClient.getHostConfiguration().getPort(), AuthScope.ANY_REALM),
                new UsernamePasswordCredentials(username, password));
    }
}

From source file:com.cloud.utils.net.HTTPUtils.java

/**
 * @param proxy//from  ww w  .  j  a  v a 2 s .  c  om
 * @param httpClient
 */
public static void setProxy(Proxy proxy, HttpClient httpClient) {
    if (proxy != null && httpClient != null) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Setting proxy with host " + proxy.getHost() + " and port " + proxy.getPort()
                    + " for host " + httpClient.getHostConfiguration().getHost() + ":"
                    + httpClient.getHostConfiguration().getPort());
        }

        httpClient.getHostConfiguration().setProxy(proxy.getHost(), proxy.getPort());
        if (proxy.getUserName() != null && proxy.getPassword() != null) {
            httpClient.getState().setProxyCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(proxy.getUserName(), proxy.getPassword()));
        }
    }
}

From source file:davmail.exchange.ExchangeSession.java

protected HttpMethod postLogonMethod(HttpClient httpClient, HttpMethod logonMethod, String userName,
        String password) throws IOException {

    setAuthFormFields(logonMethod, httpClient, password);

    // add exchange 2010 PBack cookie in compatibility mode
    httpClient.getState()// w ww.java  2s  .c  o  m
            .addCookie(new Cookie(httpClient.getHostConfiguration().getHost(), "PBack", "0", "/", null, false));

    logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);

    // test form based authentication
    checkFormLoginQueryString(logonMethod);

    // workaround for post logon script redirect
    if (!isAuthenticated()) {
        // try to get new method from script based redirection
        logonMethod = buildLogonMethod(httpClient, logonMethod);

        if (otpPreAuthFound && otpPreAuthRetries < MAX_OTP_RETRIES) {
            // A OTP pre-auth page has been found, it is needed to restart the login process.
            // This applies to both the case the user entered a good OTP code (the usual login process
            // takes place) and the case the user entered a wrong OTP code (another code will be asked to him).
            // The user has up to MAX_OTP_RETRIES chances to input a valid OTP key.
            return postLogonMethod(httpClient, logonMethod, userName, password);
        }

        if (logonMethod != null) {
            // if logonMethod is not null, try to follow redirection
            logonMethod = DavGatewayHttpClientFacade.executeFollowRedirects(httpClient, logonMethod);
            checkFormLoginQueryString(logonMethod);
            // also check cookies
            if (!isAuthenticated()) {
                throwAuthenticationFailed();
            }
        } else {
            // authentication failed
            throwAuthenticationFailed();
        }
    }

    // check for language selection form
    if (logonMethod != null && "/owa/languageselection.aspx".equals(logonMethod.getPath())) {
        // need to submit form
        logonMethod = submitLanguageSelectionForm(logonMethod);
    }
    return logonMethod;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Checks if the given client files exist on the server and internally stores duplications.<p>
 * /*w  w  w .  ja va 2s .  c o  m*/
 * Comparison is made by cutting the current directory of the file chooser from the path of the given files. 
 * The server files (VFS files) to compare to are found by the current session of the user which finds the correct site and 
 * the knowledge about the current directory. File translation rules are taken into account on the server. <p>
 * 
 * @param files the local files to check if they exist in the VFS 
 * 
 * @return one of {@link ModalDialog#ERROR_OPTION} , {@link ModalDialog#CANCEL_OPTION}, {@link ModalDialog#APPROVE_OPTION}. 
 */
int checkServerOverwrites(File[] files) {

    m_action = m_actionOverwriteCheck;
    repaint();
    int rtv = ModalDialog.ERROR_OPTION;
    // collect files
    List fileNames = new ArrayList();
    for (int i = 0; i < files.length; i++) {
        getRelativeFilePaths(files[i], fileNames);
    }

    StringBuffer uploadFiles = new StringBuffer();
    Iterator it = fileNames.iterator();
    // Http post header is limited, therefore only a ceratain amount of files may be checked 
    // for server overwrites. Solution is: multiple requests. 
    int count = 0;
    List duplications;
    // request to server
    HttpClient client = new HttpClient();
    this.m_overwrites = new ArrayList();
    try {
        while (it.hasNext()) {
            count++;
            uploadFiles.append(((String) it.next())).append('\n');

            if (((count % 40) == 0) || (!it.hasNext())) {
                // files to upload:
                PostMethod post = new PostMethod(m_targetUrl);
                Header postHeader = new Header("uploadFiles",
                        URLEncoder.encode(uploadFiles.toString(), "utf-8"));
                post.addRequestHeader(postHeader);
                // upload folder in vfs: 
                Header header2 = new Header("uploadFolder",
                        URLEncoder.encode(getParameter("filelist"), "utf-8"));
                post.addRequestHeader(header2);

                // the action constant
                post.setParameter("action", DIALOG_CHECK_OVERWRITE);

                // add jsessionid query string
                String sessionId = getParameter("sessionId");
                String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
                post.setQueryString(query);
                post.addRequestHeader(C_JSESSIONID, sessionId);

                HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
                connectionParams.setConnectionTimeout(5000);

                // add the session cookie
                client.getState();
                client.getHostConfiguration().getHost();

                HttpState initialState = new HttpState();
                URI uri = new URI(m_targetUrl, false);
                Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
                initialState.addCookie(sessionCookie);
                client.setState(initialState);
                int status = client.executeMethod(post);

                if (status == HttpStatus.SC_OK) {
                    String response = post.getResponseBodyAsString();
                    duplications = parseDuplicateFiles(URLDecoder.decode(response, "utf-8"));
                    this.m_overwrites.addAll(duplications);

                } else {
                    // continue without overwrite check 
                    String error = m_errorLine1 + "\n" + post.getStatusLine();
                    System.err.println(error);
                }

                count = 0;
                uploadFiles = new StringBuffer();
            }

        }
        if (m_overwrites.size() > 0) {
            rtv = showDuplicationsDialog(m_overwrites);
        } else {
            rtv = ModalDialog.APPROVE_OPTION;
        }

    } catch (HttpException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace(System.err);
    }

    return rtv;
}

From source file:org.opencms.applet.upload.FileUploadApplet.java

/**
 * Uploads the zipfile to the OpenCms.<p>
 * //from   w  w w  .j  a v  a2  s  . co m
 * @param uploadFile the zipfile to upload
 */
private void uploadZipFile(File uploadFile) {

    m_action = m_actionOutputUpload;
    repaint();

    PostMethod post = new PostMethod(m_targetUrl);

    try {
        Part[] parts = new Part[5];
        parts[0] = new FilePart(uploadFile.getName(), uploadFile);
        parts[1] = new StringPart("action", "submitform");
        parts[2] = new StringPart("unzipfile", "true");
        parts[3] = new StringPart("uploadfolder", m_uploadFolder);
        parts[4] = new StringPart("clientfolder", m_fileSelector.getCurrentDirectory().getAbsolutePath());

        HttpMethodParams methodParams = post.getParams();
        methodParams.setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
        MultipartRequestEntity request = new MultipartRequestEntity(parts, methodParams);
        post.setRequestEntity(request);

        // add jsessionid query string
        String sessionId = getParameter("sessionId");
        String query = ";" + C_JSESSIONID.toLowerCase() + "=" + sessionId;
        post.setQueryString(query);
        post.addRequestHeader(C_JSESSIONID, sessionId);

        HttpClient client = new HttpClient();
        HttpConnectionParams connectionParams = client.getHttpConnectionManager().getParams();
        connectionParams.setConnectionTimeout(5000);

        // add the session cookie
        client.getState();
        client.getHostConfiguration().getHost();

        HttpState initialState = new HttpState();
        URI uri = new URI(m_targetUrl, false);
        Cookie sessionCookie = new Cookie(uri.getHost(), C_JSESSIONID, sessionId, "/", null, false);
        initialState.addCookie(sessionCookie);
        client.setState(initialState);

        // no execute the file upload
        int status = client.executeMethod(post);

        if (status == HttpStatus.SC_OK) {
            //return to the specified url and frame target
            getAppletContext().showDocument(new URL(m_redirectUrl), m_redirectTargetFrame);
        } else {
            // create the error text
            String error = m_errorLine1 + "\n" + post.getStatusLine();
            //JOptionPane.showMessageDialog(this, error, "Error!", JOptionPane.ERROR_MESSAGE);
            getAppletContext().showDocument(new URL(m_errorUrl + "?action=showerror&uploaderror=" + error),
                    "explorer_files");
        }
    } catch (RuntimeException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        post.releaseConnection();
        // finally delete the zipFile on the harddisc
        uploadFile.delete();
    }
}

From source file:org.wildfly.camel.test.geocoder.subA.GeocoderHttpClientConfigurer.java

@Override
public HttpClient configureHttpClient(HttpClient httpClient) {
    LOG.debug("Configured host {}", httpClient.getHostConfiguration().getHost());
    return httpClient;
}