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:net.sf.antcontrib.net.httpclient.HttpStateType.java

public void addConfiguredCredentials(Credentials credentials) {
    if (isReference()) {
        tooManyAttributes();/*w  w w. j a  v  a  2 s .  c  om*/
    }

    AuthScope scope = new AuthScope(credentials.getHost(), credentials.getPort(), credentials.getRealm(),
            credentials.getScheme());

    UsernamePasswordCredentials c = new UsernamePasswordCredentials(credentials.getUsername(),
            credentials.getPassword());

    state.setCredentials(scope, c);
}

From source file:com.twinsoft.convertigo.engine.HttpStateEvent.java

private Credentials getCredentials() {
    Credentials credentials = null;/*from   w  ww  . j  a v  a2  s  .c om*/
    if (httpState != null) {
        if (host != null) {
            AuthScope authScope = new AuthScope(host, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME);
            credentials = httpState.getCredentials(authScope);
        }
    }
    return credentials;
}

From source file:net.sourceforge.jcctray.model.HTTPCruise.java

private static HttpClient getClient(Host host) {
    SimpleHttpConnectionManager connectionManager = new SimpleHttpConnectionManager();
    HttpConnectionManagerParams connParams = new HttpConnectionManagerParams();
    connParams.setConnectionTimeout(JCCTraySettings.getInstance().getInt(ISettingsConstants.HTTP_TIMEOUT));
    connParams.setSoTimeout(JCCTraySettings.getInstance().getInt(ISettingsConstants.HTTP_TIMEOUT));
    connectionManager.setParams(connParams);
    HttpClient client = new HttpClient(connectionManager);

    client.getParams().setAuthenticationPreemptive(true);
    if (!StringUtils.isEmptyOrNull(host.getHostName()) && !StringUtils.isEmptyOrNull(host.getPassword())) {
        UsernamePasswordCredentials credentials = new UsernamePasswordCredentials(host.getUsername(),
                host.getPassword());/* w  w w .j a  v a2 s . c om*/
        client.getState().setCredentials(new AuthScope(null, -1, null, null), credentials);
    }

    return client;
}

From source file:be.fedict.trust.Credentials.java

/**
 * Initializes the Commons HTTPClient state using the credentials stores in
 * this credential store.//  w  w  w. j  av a 2 s.  c  o  m
 * 
 * @param httpState
 */
public void init(HttpState httpState) {
    for (Credential credential : this.credentials) {
        AuthScope authScope = new AuthScope(credential.getHost(), credential.getPort(), credential.getRealm(),
                credential.getScheme());
        UsernamePasswordCredentials usernamePasswordCredentials = new UsernamePasswordCredentials(
                credential.getUsername(), credential.getPassword());
        httpState.setCredentials(authScope, usernamePasswordCredentials);
    }
}

From source file:net.sf.antcontrib.net.httpclient.HttpStateType.java

public void addConfiguredProxyCredentials(Credentials credentials) {
    if (isReference()) {
        tooManyAttributes();/*from  w ww. ja v  a2  s . co m*/
    }

    AuthScope scope = new AuthScope(credentials.getHost(), credentials.getPort(), credentials.getRealm(),
            credentials.getScheme());

    UsernamePasswordCredentials c = new UsernamePasswordCredentials(credentials.getUsername(),
            credentials.getPassword());

    state.setProxyCredentials(scope, c);
}

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

/**
 * Try to create a state./*from  w  ww .j  av  a  2 s  . co m*/
 */
public void testCreateHttpState() {
    CicsHttp cicsHttp = new CicsHttp(getName(), getEndpoint());
    HttpState state = cicsHttp.createHttpState("mainframe", 3080, "P390", "TRUC", null);
    AuthScope as = new AuthScope("mainframe", 3080, null, AuthScope.ANY_SCHEME);
    assertEquals("P390:TRUC", state.getCredentials(as).toString());
}

From source file:edu.ucsd.xmlrpc.xmlrpc.client.XmlRpcCommonsTransport.java

protected void setCredentials(XmlRpcHttpClientConfig pConfig) throws XmlRpcClientException {
    String userName = pConfig.getBasicUserName();
    if (userName != null) {
        String enc = pConfig.getBasicEncoding();
        if (enc == null) {
            enc = XmlRpcStreamConfig.UTF8_ENCODING;
        }// w w w .ja  v  a2  s. co m
        client.getParams().setParameter(HttpMethodParams.CREDENTIAL_CHARSET, enc);
        Credentials creds = new UsernamePasswordCredentials(userName, pConfig.getBasicPassword());
        AuthScope scope = new AuthScope(null, AuthScope.ANY_PORT, null, AuthScope.ANY_SCHEME);
        client.getState().setCredentials(scope, creds);
        client.getParams().setAuthenticationPreemptive(true);
    }
}

From source file:com.intuit.tank.httpclient3.TankHttpClient3.java

@Override
public void addAuth(AuthCredentials creds) {
    String host = (StringUtils.isBlank(creds.getHost()) || "*".equals(creds.getHost())) ? AuthScope.ANY_HOST
            : creds.getHost();//w  w  w  . j  a  v a  2  s  .co m
    String realm = (StringUtils.isBlank(creds.getRealm()) || "*".equals(creds.getRealm())) ? AuthScope.ANY_REALM
            : creds.getRealm();
    int port = NumberUtils.toInt(creds.getPortString(), AuthScope.ANY_PORT);
    String scheme = creds.getScheme() != null ? creds.getScheme().getRepresentation() : AuthScope.ANY_SCHEME;

    Credentials defaultcreds = new UsernamePasswordCredentials(creds.getUserName(), creds.getPassword());
    httpclient.getState().setCredentials(new AuthScope(host, port, realm, scheme), defaultcreds);
}

From source file:com.dtolabs.rundeck.core.common.impl.URLFileUpdater.java

private void updateHTTPUrl(final File destinationFile) throws FileUpdaterException {
    if (null == interaction) {
        interaction = new normalInteraction();
    }//from   w ww . ja va 2s. c om
    final Properties cacheProperties;
    if (useCaching) {
        cacheProperties = loadCacheData(cacheMetadata);
        contentTypeFromCache(cacheProperties);
    } else {
        cacheProperties = null;
    }

    final HttpClientParams params = new HttpClientParams();
    if (timeout > 0) {
        params.setConnectionManagerTimeout(timeout * 1000);
        params.setSoTimeout(timeout * 1000);
    }

    final HttpClient client = new HttpClient(params);
    AuthScope authscope = null;
    UsernamePasswordCredentials cred = null;
    boolean doauth = false;
    String cleanUrl = url.toExternalForm().replaceAll("^(https?://)([^:@/]+):[^@/]*@", "$1$2:****@");
    String urlToUse = url.toExternalForm();
    try {
        if (null != url.getUserInfo()) {
            doauth = true;
            authscope = new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : url.getDefaultPort(),
                    AuthScope.ANY_REALM, "BASIC");
            cred = new UsernamePasswordCredentials(url.getUserInfo());
            urlToUse = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).toExternalForm();
        } else if (null != username && null != password) {
            doauth = true;
            authscope = new AuthScope(url.getHost(), url.getPort() > 0 ? url.getPort() : url.getDefaultPort(),
                    AuthScope.ANY_REALM, "BASIC");
            cred = new UsernamePasswordCredentials(username + ":" + password);
            urlToUse = new URL(url.getProtocol(), url.getHost(), url.getPort(), url.getFile()).toExternalForm();
        }
    } catch (MalformedURLException e) {
        throw new FileUpdaterException("Failed to configure base URL for authentication: " + e.getMessage(), e);
    }
    if (doauth) {
        client.getParams().setAuthenticationPreemptive(true);
        client.getState().setCredentials(authscope, cred);
    }
    interaction.setClient(client);
    interaction.setMethod(new GetMethod(urlToUse));
    interaction.setFollowRedirects(true);
    if (null != acceptHeader) {
        interaction.setRequestHeader("Accept", acceptHeader);
    } else {
        interaction.setRequestHeader("Accept", "*/*");
    }

    if (useCaching) {
        applyCacheHeaders(cacheProperties, interaction);
    }

    logger.debug("Making remote request: " + cleanUrl);
    try {
        resultCode = interaction.executeMethod();
        reasonCode = interaction.getStatusText();
        if (useCaching && HttpStatus.SC_NOT_MODIFIED == resultCode) {
            logger.debug("Content NOT MODIFIED: file up to date");
        } else if (HttpStatus.SC_OK == resultCode) {
            determineContentType(interaction);

            //write to file
            FileOutputStream output = new FileOutputStream(destinationFile);
            try {
                Streams.copyStream(interaction.getResponseBodyAsStream(), output);
            } finally {
                output.close();
            }
            if (destinationFile.length() < 1) {
                //file was empty!
                if (!destinationFile.delete()) {
                    logger.warn("Failed to remove empty file: " + destinationFile.getAbsolutePath());
                }
            }
            if (useCaching) {
                cacheResponseInfo(interaction, cacheMetadata);
            }
        } else {
            throw new FileUpdaterException(
                    "Unable to retrieve content: result code: " + resultCode + " " + reasonCode);
        }
    } catch (HttpException e) {
        throw new FileUpdaterException(e);
    } catch (IOException e) {
        throw new FileUpdaterException(e);
    } finally {
        interaction.releaseConnection();
    }
}

From source file:mesquite.tol.lib.BaseHttpRequestMaker.java

/**
 * Make the http request to the specified url
 * @return If returnArray is true, a byte array containing the response bytes,
 * if false, we return an ObjectArray with the first argument being an 
 * InputStream and the second being the GetMethod that was used to make the
 * request.  The GetMethod must have releaseConnection() called on it after
 * all of the InputStream has been read.
 *///from  w  w  w  .jav  a2  s .  c om
public static Object makeHttpRequest(String url, Credentials c, String realm, boolean returnArray) {
    GetMethod getMethod = new GetMethod(url);
    Object returnValue = null;
    HttpClient client;
    try {
        client = new HttpClient();
        if (c != null) {
            client.getParams().setAuthenticationPreemptive(true);
            //client.getState().set
            //client.getState().setCredentials(new HttpAuthRealm(null, realm), c);
            //client.getState().setCredentials(realm, null, c);
            client.getState().setCredentials(
                    new AuthScope(AuthScope.ANY_HOST, AuthScope.ANY_PORT, realm, AuthScope.ANY_SCHEME), c);
        }
        int statusCode = -1;
        // We will retry up to 3 times.
        for (int attempt = 0; statusCode == -1 && attempt < 3; attempt++) {
            try {
                // execute the method.
                statusCode = client.executeMethod(getMethod);
            } catch (HttpRecoverableException e) {
                System.err.println("A recoverable exception occurred, retrying.  " + e.getMessage());
            } catch (IOException e) {
                System.err.println("Failed to download file.");
                e.printStackTrace();
                break;
            }
        }
        if (statusCode == HttpStatus.SC_OK) {
            if (returnArray) {
                returnValue = getMethod.getResponseBodyAsStream();
                InputStream stream = (InputStream) returnValue;
                byte[] bytes;
                long contentLength = getMethod.getResponseContentLength();
                if (contentLength >= 0) {
                    bytes = new byte[(int) contentLength];
                } else {
                    // it returned -1, so it doesn't know how long the
                    // length is.  We'll allocate a 5mb buffer in this case
                    bytes = new byte[MAX_BYTES];
                }
                int offset = 0;
                int nextByte = 0;
                try {
                    while ((nextByte = stream.read()) != -1) {
                        bytes[offset++] = (byte) nextByte;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } finally {
                    if (stream != null) {
                        stream.close();
                    }
                }
                byte[] newBytes = new byte[offset];
                System.arraycopy(bytes, 0, newBytes, 0, offset);
                returnValue = newBytes;
                // make sure these get garbage collected
                bytes = null;
            } else {
                InputStream stream = getMethod.getResponseBodyAsStream();
                returnValue = new Object[] { stream, getMethod };
            }
        } else {
            System.err.println("bad status code is: " + statusCode);
            returnValue = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
        try {
            getMethod.getResponseBody();
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if (returnArray) {
                getMethod.releaseConnection();
            }
        }
        returnValue = null;
    } finally {
        if (returnArray) {
            getMethod.releaseConnection();
        }
    }
    return returnValue;
}