Example usage for org.apache.commons.httpclient.auth AuthScope AuthScope

List of usage examples for org.apache.commons.httpclient.auth AuthScope AuthScope

Introduction

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

Prototype

public AuthScope(String paramString1, int paramInt, String paramString2, String paramString3) 

Source Link

Usage

From source file:com.iflytek.spider.protocol.httpclient.Http.java

/**
 * Returns an authentication scope for the specified <code>host</code>,
 * <code>port</code>, <code>realm</code> and <code>scheme</code>.
 * //from ww  w  . j av  a 2s.  c o m
 * @param host
 *            Host name or address.
 * @param port
 *            Port number.
 * @param realm
 *            Authentication realm.
 * @param scheme
 *            Authentication scheme.
 */
private static AuthScope getAuthScope(String host, int port, String realm, String scheme) {

    if (host.length() == 0)
        host = null;

    if (port < 0)
        port = -1;

    if (realm.length() == 0)
        realm = null;

    if (scheme.length() == 0)
        scheme = null;

    return new AuthScope(host, port, realm, scheme);
}

From source file:com.legstar.http.client.CicsHttp.java

/**
 * Create a state with the given credentials. A state persists from
 * request to request.// w  w w.j a v a 2  s .  com
 * @param host the host name
 * @param port the port number
 * @param userid the host user id
 * @param password the host password
 * @param realm the host realm
 * @return a new HTTP State
 */
protected HttpState createHttpState(final String host, final int port, final String userid,
        final String password, final String realm) {

    if (_log.isDebugEnabled()) {
        _log.debug("enter createHttpState");
    }

    HttpState httpState = new HttpState();

    /* If there are no credentials, assume the server might have
     * been setup without basic authentication. */
    if (password == null || password.length() == 0) {
        return httpState;
    }

    /* Username and password will be used as basic authentication
     *  credentials */
    UsernamePasswordCredentials upc = new UsernamePasswordCredentials(userid, password);
    httpState.setCredentials(new AuthScope(host, port, (realm == null || realm.length() == 0) ? null : realm,
            AuthScope.ANY_SCHEME), upc);
    return httpState;
}

From source file:com.autentia.mvn.plugin.changes.BugzillaChangesMojo.java

/**
 * Setup proxy access if we have to from settings.xml file configuration.
 * //from   ww  w.ja  v  a2  s .com
 * @param client the HttpClient
 */
private void determineProxy(final HttpClient client) {
    // see whether there is any proxy defined in maven
    Proxy proxy = null;

    String proxyHost = null;

    int proxyPort = 0;

    String proxyUser = null;

    String proxyPass = null;

    if (this.project == null) {
        this.getLog().error("No project set. No proxy info available.");

        return;
    }

    if (this.settings != null) {
        proxy = this.settings.getActiveProxy();
    }

    if (proxy != null) {
        proxyHost = this.settings.getActiveProxy().getHost();

        proxyPort = this.settings.getActiveProxy().getPort();

        proxyUser = this.settings.getActiveProxy().getUsername();

        proxyPass = this.settings.getActiveProxy().getPassword();

        this.getLog().debug(proxyPass);
    }

    if (proxyHost != null) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);

        this.getLog().debug("Using proxy: " + proxyHost + " at port " + proxyPort);

        if (proxyUser != null) {
            this.getLog().debug("Using proxy user: " + proxyUser);

            client.getState().setProxyCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                    new UsernamePasswordCredentials(proxyUser, proxyPass));
        }
    }
}

From source file:org.apache.abdera.protocol.client.AbderaClient.java

/**
 * Add authentication credentials/*  w w w .j a va 2 s.  co  m*/
 */
public AbderaClient addCredentials(String target, String realm, String scheme, Credentials credentials)
        throws URISyntaxException {
    String host = AuthScope.ANY_HOST;
    int port = AuthScope.ANY_PORT;
    if (target != null) {
        URI uri = new URI(target);
        host = uri.getHost();
        port = uri.getPort();
    }
    AuthScope scope = new AuthScope(host, port, (realm != null) ? realm : AuthScope.ANY_REALM,
            (scheme != null) ? scheme : AuthScope.ANY_SCHEME);
    client.getState().setCredentials(scope, credentials);
    return this;
}

From source file:org.apache.abdera.protocol.client.AbderaClient.java

/**
 * Specify the auth credentials for the proxy server
 */// w w  w.j  av  a 2s  . com
public AbderaClient setProxyCredentials(String host, int port, String realm, String scheme,
        Credentials credentials) {
    host = host != null ? host : AuthScope.ANY_HOST;
    port = port > -1 ? port : AuthScope.ANY_PORT;
    AuthScope scope = new AuthScope(host, port, realm != null ? realm : AuthScope.ANY_REALM,
            scheme != null ? scheme : AuthScope.ANY_SCHEME);
    client.getState().setProxyCredentials(scope, credentials);
    return this;
}

From source file:org.apache.jetspeed.portlets.sso.SSOWebContentPortlet.java

protected boolean doRequestedAuthentication(HttpClient client, HttpMethod method, RenderRequest request,
        RenderResponse response) {/*ww w.j a va 2s.  c o m*/
    if (super.doRequestedAuthentication(client, method, request, response)) {
        // already handled
        return true;
    }

    // System.out.println("SSOWebContentPortlet.doRequestedAuthentication...");

    if (method.getHostAuthState().getAuthScheme().getSchemeName().equals(BASIC_AUTH_SCHEME_NAME)) {
        // Basic authentication being requested
        String userName = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_USERNAME);
        if (userName == null)
            userName = "";
        String password = (String) request.getAttribute(SSO_REQUEST_ATTRIBUTE_PASSWORD);
        if (password == null)
            password = "";

        // System.out.println("...providing basic authentication with userName: "+userName+", and password: "+password);
        method.setDoAuthentication(true);
        AuthState state = method.getHostAuthState();
        AuthScope scope = new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, state.getRealm(),
                state.getAuthScheme().getSchemeName());
        client.getState().setCredentials(scope, new UsernamePasswordCredentials(userName, password));

        // handled!
        return true;
    } else {
        log.warn("SSOWebContentPortlent.doAuthenticate() - unexpected authentication scheme: "
                + method.getHostAuthState().getAuthScheme().getSchemeName());
    }

    // only know how to handle Basic authentication, in this context
    return false;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Returns an <code>HttpConnection</code> fully ready to attempt
 * connection. This means it sets the request method (GET or POST), headers,
 * cookies, and authorization for the URL request.
 * <p>/*  w ww .  j  a  v  a  2s.  c om*/
 * The request infos are saved into the sample result if one is provided.
 *
 * @param u
 *            <code>URL</code> of the URL request
 * @param httpMethod
 *            GET/PUT/HEAD etc
 * @param res
 *            sample result to save request infos to
 * @return <code>HttpConnection</code> ready for .connect
 * @exception IOException
 *                if an I/O Exception occurs
 */
protected HttpClient setupConnection(URL u, HttpMethodBase httpMethod, HTTPSampleResult res)
        throws IOException {

    String urlStr = u.toString();

    org.apache.commons.httpclient.URI uri = new org.apache.commons.httpclient.URI(urlStr, false);

    String schema = uri.getScheme();
    if ((schema == null) || (schema.length() == 0)) {
        schema = HTTPConstants.PROTOCOL_HTTP;
    }

    final boolean isHTTPS = HTTPConstants.PROTOCOL_HTTPS.equalsIgnoreCase(schema);
    if (isHTTPS) {
        SSLManager.getInstance(); // ensure the manager is initialised
        // we don't currently need to do anything further, as this sets the default https protocol
    }

    Protocol protocol = Protocol.getProtocol(schema);

    String host = uri.getHost();
    int port = uri.getPort();

    /*
     *  We use the HostConfiguration as the key to retrieve the HttpClient,
     *  so need to ensure that any items used in its equals/hashcode methods are
     *  not changed after use, i.e.:
     *  host, port, protocol, localAddress, proxy
     *
    */
    HostConfiguration hc = new HostConfiguration();
    hc.setHost(host, port, protocol); // All needed to ensure re-usablility

    // Set up the local address if one exists
    final InetAddress inetAddr = getIpSourceAddress();
    if (inetAddr != null) {// Use special field ip source address (for pseudo 'ip spoofing')
        hc.setLocalAddress(inetAddr);
    } else {
        hc.setLocalAddress(localAddress); // null means use the default
    }

    final String proxyHost = getProxyHost();
    final int proxyPort = getProxyPortInt();

    boolean useStaticProxy = isStaticProxy(host);
    boolean useDynamicProxy = isDynamicProxy(proxyHost, proxyPort);

    if (useDynamicProxy) {
        hc.setProxy(proxyHost, proxyPort);
        useStaticProxy = false; // Dynamic proxy overrules static proxy
    } else if (useStaticProxy) {
        if (log.isDebugEnabled()) {
            log.debug("Setting proxy: " + PROXY_HOST + ":" + PROXY_PORT);
        }
        hc.setProxy(PROXY_HOST, PROXY_PORT);
    }

    Map<HostConfiguration, HttpClient> map = httpClients.get();
    // N.B. HostConfiguration.equals() includes proxy settings in the compare.
    HttpClient httpClient = map.get(hc);

    if (httpClient != null && resetSSLContext && isHTTPS) {
        httpClient.getHttpConnectionManager().closeIdleConnections(-1000);
        httpClient = null;
        JsseSSLManager sslMgr = (JsseSSLManager) SSLManager.getInstance();
        sslMgr.resetContext();
        resetSSLContext = false;
    }

    if (httpClient == null) {
        httpClient = new HttpClient(new SimpleHttpConnectionManager());
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER,
                new DefaultHttpMethodRetryHandler(RETRY_COUNT, false));
        if (log.isDebugEnabled()) {
            log.debug("Created new HttpClient: @" + System.identityHashCode(httpClient));
        }
        httpClient.setHostConfiguration(hc);
        map.put(hc, httpClient);
    } else {
        if (log.isDebugEnabled()) {
            log.debug("Reusing the HttpClient: @" + System.identityHashCode(httpClient));
        }
    }

    // Set up any required Proxy credentials
    if (useDynamicProxy) {
        String user = getProxyUser();
        if (user.length() > 0) {
            httpClient.getState().setProxyCredentials(
                    new AuthScope(proxyHost, proxyPort, null, AuthScope.ANY_SCHEME),
                    new NTCredentials(user, getProxyPass(), localHost, PROXY_DOMAIN));
        } else {
            httpClient.getState().clearProxyCredentials();
        }
    } else {
        if (useStaticProxy) {
            if (PROXY_USER.length() > 0) {
                httpClient.getState().setProxyCredentials(
                        new AuthScope(PROXY_HOST, PROXY_PORT, null, AuthScope.ANY_SCHEME),
                        new NTCredentials(PROXY_USER, PROXY_PASS, localHost, PROXY_DOMAIN));
            }
        } else {
            httpClient.getState().clearProxyCredentials();
        }
    }

    int rto = getResponseTimeout();
    if (rto > 0) {
        httpMethod.getParams().setSoTimeout(rto);
    }

    int cto = getConnectTimeout();
    if (cto > 0) {
        httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(cto);
    }

    // Allow HttpClient to handle the redirects:
    httpMethod.setFollowRedirects(getAutoRedirects());

    // a well-behaved browser is supposed to send 'Connection: close'
    // with the last request to an HTTP server. Instead, most browsers
    // leave it to the server to close the connection after their
    // timeout period. Leave it to the JMeter user to decide.
    if (getUseKeepAlive()) {
        httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.KEEP_ALIVE);
    } else {
        httpMethod.setRequestHeader(HTTPConstants.HEADER_CONNECTION, HTTPConstants.CONNECTION_CLOSE);
    }

    setConnectionHeaders(httpMethod, u, getHeaderManager(), getCacheManager());
    String cookies = setConnectionCookie(httpMethod, u, getCookieManager());

    setConnectionAuthorization(httpClient, u, getAuthManager());

    if (res != null) {
        res.setCookies(cookies);
    }

    return httpClient;
}

From source file:org.apache.jmeter.protocol.http.sampler.HTTPHC3Impl.java

/**
 * Extracts all the required authorization for that particular URL request
 * and sets it in the <code>HttpMethod</code> passed in.
 *
 * @param client the HttpClient object/* www . j  av a 2s .  c  o m*/
 *
 * @param u
 *            <code>URL</code> of the URL request
 * @param authManager
 *            the <code>AuthManager</code> containing all the authorisations for
 *            this <code>UrlConfig</code>
 */
private void setConnectionAuthorization(HttpClient client, URL u, AuthManager authManager) {
    HttpState state = client.getState();
    if (authManager != null) {
        HttpClientParams params = client.getParams();
        Authorization auth = authManager.getAuthForURL(u);
        if (auth != null) {
            String username = auth.getUser();
            String realm = auth.getRealm();
            String domain = auth.getDomain();
            if (log.isDebugEnabled()) {
                log.debug(username + " >  D=" + username + " D=" + domain + " R=" + realm);
            }
            state.setCredentials(new AuthScope(u.getHost(), u.getPort(), realm.length() == 0 ? null : realm //"" is not the same as no realm
                    , AuthScope.ANY_SCHEME),
                    // NT Includes other types of Credentials
                    new NTCredentials(username, auth.getPass(), localHost, domain));
            // We have credentials - should we set pre-emptive authentication?
            if (canSetPreEmptive) {
                log.debug("Setting Pre-emptive authentication");
                params.setAuthenticationPreemptive(true);
            }
        } else {
            state.clearCredentials();
            if (canSetPreEmptive) {
                params.setAuthenticationPreemptive(false);
            }
        }
    } else {
        state.clearCredentials();
    }
}

From source file:org.apache.maven.plugin.jira.AbstractJiraDownloader.java

/**
 * Check and prepare for basic authentication.
 *
 * @param client The client to prepare//from   ww  w  . j a  v a 2  s.c  o m
 */
private void prepareBasicAuthentication(HttpClient client) {
    if ((webUser != null) && (webUser.length() > 0)) {
        client.getParams().setAuthenticationPreemptive(true);

        Credentials defaultcreds = new UsernamePasswordCredentials(webUser, webPassword);

        getLog().debug("Using username: " + webUser + " for Basic Authentication.");

        client.getState().setCredentials(new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                defaultcreds);
    }
}

From source file:org.apache.maven.plugin.jira.AbstractJiraDownloader.java

/**
 * Setup proxy access if we have to./*from  w  w w  . j a  v a 2s .c  o m*/
 *
 * @param client  the HttpClient
 */
private void determineProxy(String jiraUrl, HttpClient client) {
    // see whether there is any proxy defined in maven
    Proxy proxy = null;

    String proxyHost = null;

    int proxyPort = 0;

    String proxyUser = null;

    String proxyPass = null;

    if (project == null) {
        getLog().error("No project set. No proxy info available.");

        return;
    }

    if (settings != null) {
        proxy = settings.getActiveProxy();
    }

    if (proxy != null) {

        ProxyInfo proxyInfo = new ProxyInfo();
        proxyInfo.setNonProxyHosts(proxy.getNonProxyHosts());

        // Get the host out of the JIRA URL
        URL url = null;
        try {
            url = new URL(jiraUrl);
        } catch (MalformedURLException e) {
            getLog().error("Invalid JIRA URL: " + jiraUrl + ". " + e.getMessage());
        }
        String jiraHost = null;
        if (url != null) {
            jiraHost = url.getHost();
        }

        // Validation of proxy method copied from org.apache.maven.wagon.proxy.ProxyUtils.
        // @todo Can use original when maven-changes-plugin requires a more recent version of Maven

        //if ( ProxyUtils.validateNonProxyHosts( proxyInfo, jiraHost ) )
        if (JiraHelper.validateNonProxyHosts(proxyInfo, jiraHost)) {
            return;
        }

        proxyHost = settings.getActiveProxy().getHost();

        proxyPort = settings.getActiveProxy().getPort();

        proxyUser = settings.getActiveProxy().getUsername();

        proxyPass = settings.getActiveProxy().getPassword();

        getLog().debug(proxyPass);
    }

    if (proxyHost != null) {
        client.getHostConfiguration().setProxy(proxyHost, proxyPort);

        getLog().debug("Using proxy: " + proxyHost + " at port " + proxyPort);

        if (proxyUser != null) {
            getLog().debug("Using proxy user: " + proxyUser);

            client.getState().setProxyCredentials(
                    new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME),
                    new UsernamePasswordCredentials(proxyUser, proxyPass));
        }
    }
}