Example usage for org.apache.commons.httpclient.auth AuthPolicy BASIC

List of usage examples for org.apache.commons.httpclient.auth AuthPolicy BASIC

Introduction

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

Prototype

String BASIC

To view the source code for org.apache.commons.httpclient.auth AuthPolicy BASIC.

Click Source Link

Usage

From source file:org.iavante.sling.transcodingServer.impl.TranscodingManagerImpl.java

@SuppressWarnings("unchecked")
private String notificateStatus(String mystatus, Node jobNode) {
    log.info("notificatingStatus: reading properties");
    String response = "";

    String notification_url = null;
    String gadUser = null;/*ww  w  . j  a va 2  s  .c  o  m*/
    String gadPassword = null;

    HttpClient client = null;
    List authPrefs = new ArrayList(2);
    client = new HttpClient();
    Credentials defaultcreds;
    // first of all. We have to take the useful data
    try {

        notification_url = jobNode.getProperty("notification_url").getValue().getString();

        gadUser = Constantes.getGADuser();
        gadPassword = Constantes.getGADpassword();

    } catch (ValueFormatException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (PathNotFoundException e) {
        e.printStackTrace();
    } catch (RepositoryException e) {
        e.printStackTrace();
    }
    // Using the hhtp client. This has to be authenticated
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials(gadUser, gadPassword);
    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    // Using the POST Method
    PostMethod post_notification = new PostMethod(notification_url);
    post_notification.setDoAuthentication(true);
    NameValuePair[] data_notification = { new NameValuePair("sling:resourceType", "gad/transformation"),
            new NameValuePair("state", mystatus) };
    post_notification.setRequestBody(data_notification);
    post_notification.setDoAuthentication(true);
    try {
        log.info("notificatingStatus...");
        client.executeMethod(post_notification);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }
    // Response in Status
    int status = post_notification.getStatusCode();
    post_notification.releaseConnection();
    if (status == 200) {
        response = "OK. Notificated. Status =" + status;
        log.info(response);
    } else {
        response = "Error notificating. Status =" + status;
        log.error(response);
    }
    return response;
}

From source file:org.iavante.sling.transcodingServer.TranscodingServerTestIT.java

protected void setUp() {

    Map<String, String> envs = System.getenv();
    Set<String> keys = envs.keySet();

    Iterator<String> it = keys.iterator();
    boolean hashost = false;
    while (it.hasNext()) {
        String key = (String) it.next();

        if (key.compareTo(HOSTVAR) == 0) {
            SLING_URL = SLING_URL + (String) envs.get(key);
            hashost = true;//from  ww w.  j  ava 2s  .  c  o  m
        }
    }

    if (hashost == false)
        SLING_URL = SLING_URL + HOSTPREDEF;

    client = new HttpClient();

    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials("admin", "admin");

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultcreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);

    // Create a wrong job

    PostMethod post_create_job = new PostMethod(SLING_URL + JOBS_PENDING_URL);

    post_create_job.setDoAuthentication(true);

    NameValuePair[] data_create_job = { new NameValuePair("sling:resourceType", resourceType),
            new NameValuePair("source_location", wrong_source_location),
            new NameValuePair("target_location", wrong_target_location),
            new NameValuePair("executable", executable), new NameValuePair("title", title),
            new NameValuePair("notification_url", notification_url),
            new NameValuePair("extern_storage_server", extern_storage_server),
            new NameValuePair("extern_storage_url", extern_storage_url), new NameValuePair("jcr:created", ""),
            new NameValuePair("jcr:createdBy", ""), new NameValuePair("jcr:lastModified", ""),
            new NameValuePair("jcr:lastModifiedBy", "") };

    post_create_job.setRequestBody(data_create_job);

    try {
        client.executeMethod(post_create_job);
    } catch (HttpException e1) {
        e1.printStackTrace();
    } catch (IOException e1) {
        e1.printStackTrace();
    }

    post_create_job.releaseConnection();

}

From source file:org.iavante.uploader.ifaces.impl.UploadServiceImpl.java

/**
 * Initial http client configuration.//from ww w  . j av a  2s . c om
 */
private void setup() {
    client = new HttpClient();

    defaultCreds = new UsernamePasswordCredentials("admin", "admin");

    authPrefs = new ArrayList(2);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);

    client.getParams().setAuthenticationPreemptive(true);
    client.getState().setCredentials(AuthScope.ANY, defaultCreds);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
}

From source file:org.iavante.uploader.ifaces.UploadServiceIT.java

protected void setUp() {

    System.out.println("setup, inicio");
    System.out.println("setup, IUploadService=" + uploadService);

    Map<String, String> envs = System.getenv();
    Set<String> keys = envs.keySet();

    Iterator<String> it = keys.iterator();
    boolean hashost = false;
    while (it.hasNext()) {
        String key = (String) it.next();

        if (key.compareTo(HOSTVAR) == 0) {
            SLING_URL = SLING_URL + (String) envs.get(key);
            hashost = true;/*from   www  . j  a  va  2 s.  c  om*/
        }
    }
    if (hashost == false)
        SLING_URL = SLING_URL + HOSTPREDEF;

    client = new HttpClient();
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.BASIC);
    defaultcreds = new UsernamePasswordCredentials("admin", "admin");

    System.out.println("setup, fin");

}

From source file:org.infoglue.igide.helper.HTTPClientHelper.java

public HTTPClientHelper(URL baseurl, String username, String password) {
    HttpClientParams params = new HttpClientParams(HttpClientParams.getDefaultParams());

    client = new HttpClient(params);

    Credentials defaultcreds = new UsernamePasswordCredentials(username, password);
    client.getState().setCredentials(new AuthScope(baseurl.getHost(), baseurl.getPort(), AuthScope.ANY_REALM),
            defaultcreds);/*from   www  . j  a  va 2  s .  c  om*/

    List<String> authPrefs = new ArrayList<String>(2);
    authPrefs.add(AuthPolicy.BASIC);
    authPrefs.add(AuthPolicy.DIGEST);
    authPrefs.add(AuthPolicy.NTLM);
    client.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
}

From source file:org.mule.modules.constantcontact.RequestExecutor.java

public RequestExecutor(String apiKey, String username, String password) {
    String loginUsername = apiKey + "%" + username;
    httpclient.getCredentialsProvider().setCredentials(AuthScope.ANY,
            new UsernamePasswordCredentials(loginUsername, password));
    httpclient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, Arrays.asList(AuthPolicy.BASIC));
}

From source file:org.ow2.petals.binding.soap.listener.outgoing.AbstractExternalServiceCaller.java

/**
 * Getting the basic authentication parameters for the outgoing SOAP
 * request.//from w ww.  j  a  v  a2  s .co  m
 * 
 * @param extensions
 * @param options
 * @return
 */
@SuppressWarnings("unchecked")
protected final static HttpTransportProperties.Authenticator retrieveBasicAuthentication(
        final ConfigurationExtensions extensions, final Options options) {
    HttpTransportProperties.Authenticator basicAuthentication = null;
    final String username = extensions.get(BASIC_AUTH_USERNAME);
    String password = extensions.get(BASIC_AUTH_PASSWORD);

    if (username != null) {
        if (password == null) {
            password = "";
        }

        basicAuthentication = new HttpTransportProperties.Authenticator();
        final List schemes = new ArrayList();
        schemes.add(AuthPolicy.BASIC);
        basicAuthentication.setAuthSchemes(schemes);
        basicAuthentication.setUsername(username);
        basicAuthentication.setPassword(password);
        basicAuthentication.setPreemptiveAuthentication(true);
        options.setProperty(org.apache.axis2.transport.http.HTTPConstants.AUTHENTICATE, basicAuthentication);
    }

    return basicAuthentication;
}

From source file:org.sonatype.nexus.bundle.launcher.support.RequestUtils.java

/**
 * Execute HttpMethod with default Nexus admin credentials
 *
 * @param method/*  w ww.j  a  v  a2s .  c o  m*/
 * @return
 * @throws HttpException
 * @throws IOException
 */
public static HttpMethod executeHTTPClientMethodAsAdmin(final HttpMethod method)
        throws HttpException, IOException {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(5000);

    httpClient.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("admin", "admin123"));
    List<String> authPrefs = new ArrayList<String>(1);
    authPrefs.add(AuthPolicy.BASIC);
    httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    httpClient.getParams().setAuthenticationPreemptive(true);

    try {
        httpClient.executeMethod(method);
        method.getResponseBodyAsString(); // forced consumption of response I guess
        return method;
    } finally {
        method.releaseConnection();

        // force socket cleanup
        HttpConnectionManager mgr = httpClient.getHttpConnectionManager();

        if (mgr instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) mgr).shutdown();

        }
    }
}

From source file:org.sonatype.nexus.integrationtests.NexusRestClient.java

/**
 * Execute a HTTPClient method, optionally in the context of a test.
 * <p/>//from  w w  w.  j  ava2  s .  c o m
 * NOTE: Before being returned, {@link org.apache.commons.httpclient.HttpMethod#releaseConnection()} is called on the {@link org.apache.commons.httpclient.HttpMethod} instance,
 * therefore subsequent calls to get response body as string may return nulls.
 *
 * @param method         the method to execute
 * @param useTestContext if true, execute this request in the context of a Test, false means ignore the testContext
 *                       settings
 * @return the HttpMethod instance passed into this method
 * @throws java.io.IOException
 */
public HttpMethod executeHTTPClientMethod(final HttpMethod method, final boolean useTestContext)
        throws IOException {
    HttpClient httpClient = new HttpClient();
    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(10000);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(10000);

    if (useTestContext) {
        if (testContext.isSecureTest()) {
            httpClient.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(testContext.getUsername(), testContext.getPassword()));

            List<String> authPrefs = new ArrayList<String>(1);
            authPrefs.add(AuthPolicy.BASIC);
            httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
            httpClient.getParams().setAuthenticationPreemptive(true);
        }
    }

    try {
        httpClient.executeMethod(method);
        method.getResponseBodyAsString(); // forced consumption of response I guess
        return method;
    } finally {
        method.releaseConnection();

        // force socket cleanup
        HttpConnectionManager mgr = httpClient.getHttpConnectionManager();

        if (mgr instanceof SimpleHttpConnectionManager) {
            ((SimpleHttpConnectionManager) mgr).shutdown();

        }
    }
}

From source file:org.sonatype.nexus.proxy.storage.remote.commonshttpclient.HttpClientProxyUtil.java

public static void applyProxyToHttpClient(HttpClient httpClient, RemoteStorageContext ctx, Logger logger) {
    httpClient.setHttpConnectionManager(new CustomMultiThreadedHttpConnectionManager());

    // getting the timeout from RemoteStorageContext. The value we get depends on per-repo and global settings.
    // The value will "cascade" from repo level to global level, see imple of it.
    int timeout = ctx.getRemoteConnectionSettings().getConnectionTimeout();

    // getting the connection pool size, using a little trick to allow us "backdoor" to tune it using system
    // properties, but defaulting it to the same we had before (httpClient defaults)
    int connectionPoolSize = SystemPropertiesHelper.getInteger(CONNECTION_POOL_SIZE_KEY,
            MultiThreadedHttpConnectionManager.DEFAULT_MAX_TOTAL_CONNECTIONS);

    httpClient.getHttpConnectionManager().getParams().setConnectionTimeout(timeout);
    httpClient.getHttpConnectionManager().getParams().setSoTimeout(timeout);
    // httpClient.getHttpConnectionManager().getParams().setTcpNoDelay( true );
    httpClient.getHttpConnectionManager().getParams().setMaxTotalConnections(connectionPoolSize);
    // NOTE: connPool is _per_ repo, hence all of those will connect to same host (unless mirrors are used)
    // so, we are violating intentionally the RFC and we let the whole pool size to chase same host
    httpClient.getHttpConnectionManager().getParams()
            .setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, connectionPoolSize);

    // Setting auth if needed
    HostConfiguration httpConfiguration = httpClient.getHostConfiguration();

    // BASIC and DIGEST auth only
    RemoteAuthenticationSettings ras = ctx.getRemoteAuthenticationSettings();

    boolean isSimpleAuthUsed = false;
    boolean isNtlmUsed = false;

    if (ras != null) {
        List<String> authPrefs = new ArrayList<String>(2);
        authPrefs.add(AuthPolicy.DIGEST);
        authPrefs.add(AuthPolicy.BASIC);

        if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
            // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras;

            // TODO - implement this
        } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
            NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

            // Using NTLM auth, adding it as first in policies
            authPrefs.add(0, AuthPolicy.NTLM);

            logger(logger).info("... authentication setup for NTLM domain '{}'", nras.getNtlmDomain());

            httpConfiguration.setHost(nras.getNtlmHost());

            httpClient.getState().setCredentials(AuthScope.ANY, new NTCredentials(nras.getUsername(),
                    nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()));

            isNtlmUsed = true;//  w  w w .  ja v a2s  .  c  om
        } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
            UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

            // Using Username/Pwd auth, will not add NTLM
            logger(logger).info("... authentication setup for remote storage with username '{}'",
                    uras.getUsername());

            httpClient.getState().setCredentials(AuthScope.ANY,
                    new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()));

            isSimpleAuthUsed = true;
        }

        httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
    }

    RemoteProxySettings rps = ctx.getRemoteProxySettings();

    boolean isProxyUsed = false;

    if (rps.isEnabled()) {
        isProxyUsed = true;

        logger(logger).info("... proxy setup with host '{}'", rps.getHostname());

        httpConfiguration.setProxy(rps.getHostname(), rps.getPort());

        // check if we have non-proxy hosts
        if (rps.getNonProxyHosts() != null && !rps.getNonProxyHosts().isEmpty()) {
            Set<Pattern> nonProxyHostPatterns = new HashSet<Pattern>(rps.getNonProxyHosts().size());
            for (String nonProxyHostRegex : rps.getNonProxyHosts()) {
                try {
                    nonProxyHostPatterns.add(Pattern.compile(nonProxyHostRegex, Pattern.CASE_INSENSITIVE));
                } catch (PatternSyntaxException e) {
                    logger(logger).warn("Invalid non proxy host regex: {}", nonProxyHostRegex, e);
                }
            }
            httpConfiguration.getParams().setParameter(
                    CustomMultiThreadedHttpConnectionManager.NON_PROXY_HOSTS_PATTERNS_KEY,
                    nonProxyHostPatterns);
        }

        if (rps.getProxyAuthentication() != null) {
            ras = rps.getProxyAuthentication();

            List<String> authPrefs = new ArrayList<String>(2);
            authPrefs.add(AuthPolicy.DIGEST);
            authPrefs.add(AuthPolicy.BASIC);

            if (ras instanceof ClientSSLRemoteAuthenticationSettings) {
                // ClientSSLRemoteAuthenticationSettings cras = (ClientSSLRemoteAuthenticationSettings) ras;

                // TODO - implement this
            } else if (ras instanceof NtlmRemoteAuthenticationSettings) {
                NtlmRemoteAuthenticationSettings nras = (NtlmRemoteAuthenticationSettings) ras;

                // Using NTLM auth, adding it as first in policies
                authPrefs.add(0, AuthPolicy.NTLM);

                if (ctx.getRemoteAuthenticationSettings() != null && (ctx
                        .getRemoteAuthenticationSettings() instanceof NtlmRemoteAuthenticationSettings)) {
                    logger(logger).warn("... Apache Commons HttpClient 3.x is unable to use NTLM auth scheme\n"
                            + " for BOTH server side and proxy side authentication!\n"
                            + " You MUST reconfigure server side auth and use BASIC/DIGEST scheme\n"
                            + " if you have to use NTLM proxy, otherwise it will not work!\n"
                            + " *** SERVER SIDE AUTH OVERRIDDEN");
                }

                logger(logger).info("... proxy authentication setup for NTLM domain '{}'",
                        nras.getNtlmDomain());

                httpConfiguration.setHost(nras.getNtlmHost());

                httpClient.getState().setProxyCredentials(AuthScope.ANY, new NTCredentials(nras.getUsername(),
                        nras.getPassword(), nras.getNtlmHost(), nras.getNtlmDomain()));

                isNtlmUsed = true;
            } else if (ras instanceof UsernamePasswordRemoteAuthenticationSettings) {
                UsernamePasswordRemoteAuthenticationSettings uras = (UsernamePasswordRemoteAuthenticationSettings) ras;

                // Using Username/Pwd auth, will not add NTLM
                logger(logger).info("... proxy authentication setup for remote storage with username '{}'",
                        uras.getUsername());

                httpClient.getState().setProxyCredentials(AuthScope.ANY,
                        new UsernamePasswordCredentials(uras.getUsername(), uras.getPassword()));
            }

            httpClient.getParams().setParameter(AuthPolicy.AUTH_SCHEME_PRIORITY, authPrefs);
        }
    }

    // set preemptive only for simplest scenario:
    // no proxy and BASIC auth is used
    if (isSimpleAuthUsed && !isProxyUsed) {
        logger(logger)
                .info("... simple scenario: simple authentication used with no proxy in between target and us,"
                        + " will use preemptive authentication");

        // we have authentication, let's do it preemptive
        httpClient.getParams().setAuthenticationPreemptive(true);
    }

    // mark the fact that NTLM is in use
    // but ONLY IF IT CHANGED!
    // Otherwise, doing it always, actually marks the ctx itself as "changed", causing an avalanche of other
    // consequences, like resetting all the HTTP clients of all remote storages (coz they think there is a change
    // in proxy or remote connection settings, etc).
    final Boolean isNtlmUsedOldValue = (Boolean) ctx.getContextObject(NTLM_IS_IN_USE_KEY);
    if (isNtlmUsedOldValue == null || isNtlmUsedOldValue.booleanValue() != isNtlmUsed) {
        if (isNtlmUsed) {
            ctx.putContextObject(NTLM_IS_IN_USE_KEY, Boolean.TRUE);
        } else {
            ctx.putContextObject(NTLM_IS_IN_USE_KEY, Boolean.FALSE);
        }
    }
}