Example usage for org.apache.commons.httpclient UsernamePasswordCredentials UsernamePasswordCredentials

List of usage examples for org.apache.commons.httpclient UsernamePasswordCredentials UsernamePasswordCredentials

Introduction

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

Prototype

public UsernamePasswordCredentials(String paramString) 

Source Link

Usage

From source file:com.gs.jrpip.client.ThankYouWriterTest.java

public void testAddRequest() throws Exception {
    AuthenticatedUrl url = new AuthenticatedUrl(this.getJrpipUrl(),
            new UsernamePasswordCredentials("username"));
    Cookie cookie1 = new Cookie("domain", "cookie1", "val1", "/", 1000, false);
    Cookie cookie2 = new Cookie("domain", "cookie2", "val2", "/", 1000, false);
    Cookie cookie3 = new Cookie("domain", "cookie3", "val3", "/", 1000, false);
    ThankYouWriter thankYouWriter = ThankYouWriter.getINSTANCE();
    thankYouWriter.stopThankYouThread();
    thankYouWriter.addRequest(url, new Cookie[] { cookie1, cookie2, cookie3 }, new RequestId(1));
    thankYouWriter.addRequest(url, new Cookie[] { cookie1, cookie2, cookie3 }, new RequestId(2)); // same combination
    thankYouWriter.addRequest(url, new Cookie[] { cookie3, cookie2, cookie1 }, new RequestId(3)); // cookie order changed
    thankYouWriter.addRequest(url, new Cookie[] { cookie3 }, new RequestId(4)); // mismatch cookies
    thankYouWriter.addRequest(url, new Cookie[] {}, new RequestId(5)); // no cookies
    thankYouWriter.addRequest(url, null, new RequestId(6)); // null cookies

    assertEquals(3, thankYouWriter.getPendingRequests());
}

From source file:com.arjuna.qa.junit.HttpUtils.java

public static HttpMethodBase accessURL(URL url, String realm, int expectedHttpCode, Header[] hdrs, int type)
        throws Exception {
    HttpClient httpConn = new HttpClient();
    HttpMethodBase request = createMethod(url, type);

    int hdrCount = hdrs != null ? hdrs.length : 0;
    for (int n = 0; n < hdrCount; n++)
        request.addRequestHeader(hdrs[n]);
    try {//  w  w  w .ja va  2s  .com
        System.err.println("Connecting to: " + url);
        String userInfo = url.getUserInfo();

        if (userInfo != null) {
            UsernamePasswordCredentials auth = new UsernamePasswordCredentials(userInfo);
            httpConn.getState().setCredentials(realm, url.getHost(), auth);
        }
        System.err.println("RequestURI: " + request.getURI());
        int responseCode = httpConn.executeMethod(request);
        String response = request.getStatusText();
        System.err.println("responseCode=" + responseCode + ", response=" + response);
        String content = request.getResponseBodyAsString();
        System.err.println(content);
        // Validate that we are seeing the requested response code
        if (responseCode != expectedHttpCode) {
            throw new IOException("Expected reply code:" + expectedHttpCode + ", actual=" + responseCode);
        }
    } catch (IOException e) {
        throw e;
    }
    return request;
}

From source file:com.sun.jersey.client.apache.config.ApacheHttpClientState.java

/**
 *
 * Sets the credentials for the given authentication scope.  Any
 * previous credentials for the given scope will be overwritten.
 *
 * @param realm The authentication realm.  The null realm
 * signifies default credentials for the given host, which should
 * be used when no credentials have been explicitly supplied for
 * the challenging realm./*w  ww  . j  a  v  a  2 s.  c om*/
 * @param host The host the realm belongs to. The null host
 * signifies default credentials which should be used when no
 * credentials have been explicitly supplied for the challenging
 * host.
 * @param port The port the realm belongs to. A negitive port
 * signifies the credentials are applicaple to any port when no
 * credentials have been explicitly supplied for the challenging
 * port.
 * @param usernamepassword The username:password formed string.
 */
public void setCredentials(String realm, String host, int port, String usernamepassword) {
    AuthScope authScope = new AuthScope(host, port, realm);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(usernamepassword);

    getHttpState().setCredentials(authScope, creds);
}

From source file:com.gist.twitter.TwitterClient.java

/**
 * Turns a collection of "username:password" credentials into a collection
 * of UsernamePasswordCredentials for use with HttpClient.
 *///from ww  w. jav a 2 s . c om
private Collection<UsernamePasswordCredentials> createCredentials(Collection<String> logins) {
    ArrayList<UsernamePasswordCredentials> result = new ArrayList<UsernamePasswordCredentials>();
    for (String login : logins) {
        result.add(new UsernamePasswordCredentials(login));
    }
    return result;
}

From source file:com.sun.jersey.client.apache.config.ApacheHttpClientState.java

/**
 * Sets the proxy credentials for the given authentication scope.
 * Any previous credentials for the given scope will be
 * overwritten.//from w  w w  .ja  v  a 2  s . c  o m
 *
 * @param realm The authentication realm.  The null realm
 * signifies default credentials for the given host, which should
 * be used when no credentials have been explicitly supplied for
 * the challenging realm.
 * @param host The host the realm belongs to. The null host
 * signifies default credentials which should be used when no
 * credentials have been explicitly supplied for the challenging
 * host.
 * @param port The port the realm belongs to. A negitive port
 * signifies the credentials are applicaple to any port when no
 * credentials have been explicitly supplied for the challenging
 * port.
 * @param usernamepassword The username:password formed string.
 */
public void setProxyCredentials(String realm, String host, int port, String usernamepassword) {
    AuthScope authScope = new AuthScope(host, port, realm);
    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(usernamepassword);

    getHttpState().setProxyCredentials(authScope, creds);
}

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  .j  a  v a  2 s .co  m*/
    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:de.innovationgate.webgate.api.rss2.SimpleRSS.java

private InputStream retrievePage(String url, NativeQueryOptions nativeOptions) throws WGQueryException {

    try {/* w w  w. j av a2 s.c  o m*/

        // Retrieve from web
        HttpClient client = WGFactory.getHttpClientFactory().createHttpClient();
        client.setConnectionTimeout(10000);
        if (_useProxy) {
            client.getHostConfiguration().setProxy(_proxyHost, _proxyPort);
            if (_proxyCredentials != null) {
                Credentials credentials;
                if (_proxyDomain != null) {
                    List elements = WGUtils.deserializeCollection(_proxyCredentials, ":");
                    credentials = new NTCredentials((String) elements.get(0), (String) elements.get(1),
                            _proxyHost, _proxyDomain);
                } else {
                    credentials = new UsernamePasswordCredentials(_proxyCredentials);

                }
                client.getState().setProxyCredentials(null, _proxyHost, credentials);

            }
        }
        HttpMethod method = new GetMethod(url);
        method.setFollowRedirects(true);
        method.setStrictMode(false);

        if (nativeOptions.containsKey(QUERYOPTION_USER) && nativeOptions.containsKey(QUERYOPTION_PWD)) {
            method.setDoAuthentication(true);
            client.getParams().setAuthenticationPreemptive(true);
            client.getState().setCredentials(AuthScope.ANY, new UsernamePasswordCredentials(
                    nativeOptions.get(QUERYOPTION_USER), nativeOptions.get(QUERYOPTION_PWD)));
        }

        client.executeMethod(method);

        // Read response. Wrap content decoder if necessary.
        InputStream inStream = method.getResponseBodyAsStream();

        // Return InputStream from given URL
        return inStream;
    } catch (MalformedURLException e) {
        throw new WGQueryException("Malformed feed URL", url, e);
    } catch (IOException e) {
        throw new WGQueryException("IO Exception retrieving feed", url, e);
    }
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java

/** ping the server and pass the announcements between the two **/
void ping(final boolean force) {
    if (autoStopped) {
        // then we suppress any further pings!
        logger.debug("ping: autoStopped=true, hence suppressing any further pings.");
        return;/*from w  w w.j  a  v a 2 s . com*/
    }
    if (force) {
        backoffPeriodEnd = -1;
    } else if (backoffPeriodEnd > 0) {
        if (System.currentTimeMillis() < backoffPeriodEnd) {
            logger.debug("ping: not issueing a heartbeat due to backoff instruction from peer.");
            return;
        } else {
            logger.debug("ping: backoff period ended, issuing another ping now.");
        }
    }
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("ping: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }
    HttpClient httpClient = new HttpClient();
    final PutMethod method = new PutMethod(uri);
    Announcement resultingAnnouncement = null;
    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            httpClient.getState()
                    .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c);
        }

        Announcement topologyAnnouncement = new Announcement(clusterViewService.getSlingId());
        topologyAnnouncement.setServerInfo(serverInfo);
        final ClusterView clusterView = clusterViewService.getClusterView();
        topologyAnnouncement.setLocalCluster(clusterView);
        if (force) {
            logger.debug("ping: sending a resetBackoff");
            topologyAnnouncement.setResetBackoff(true);
        }
        announcementRegistry.addAllExcept(topologyAnnouncement, clusterView, new AnnouncementFilter() {

            public boolean accept(final String receivingSlingId, final Announcement announcement) {
                // filter out announcements that are of old cluster instances
                // which I dont really have in my cluster view at the moment
                final Iterator<InstanceDescription> it = clusterViewService.getClusterView().getInstances()
                        .iterator();
                while (it.hasNext()) {
                    final InstanceDescription instance = it.next();
                    if (instance.getSlingId().equals(receivingSlingId)) {
                        // then I have the receiving instance in my cluster view
                        // all fine then
                        return true;
                    }
                }
                // looks like I dont have the receiving instance in my cluster view
                // then I should also not propagate that announcement anywhere
                return false;
            }
        });
        final String p = requestValidator.encodeMessage(topologyAnnouncement.asJSON());

        if (logger.isDebugEnabled()) {
            logger.debug("ping: topologyAnnouncement json is: " + p);
        }
        requestValidator.trustMessage(method, p);
        if (config.isGzipConnectorRequestsEnabled()) {
            // tell the server that the content is gzipped:
            method.addRequestHeader("Content-Encoding", "gzip");
            // and gzip the body:
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            final GZIPOutputStream gzipOut = new GZIPOutputStream(baos);
            gzipOut.write(p.getBytes("UTF-8"));
            gzipOut.close();
            final byte[] gzippedEncodedJson = baos.toByteArray();
            method.setRequestEntity(new ByteArrayRequestEntity(gzippedEncodedJson, "application/json"));
            lastRequestEncoding = "gzip";
        } else {
            // otherwise plaintext:
            method.setRequestEntity(new StringRequestEntity(p, "application/json", "UTF-8"));
            lastRequestEncoding = "plaintext";
        }
        // independent of request-gzipping, we do accept the response to be gzipped,
        // so indicate this to the server:
        method.addRequestHeader("Accept-Encoding", "gzip");
        DefaultHttpMethodRetryHandler retryhandler = new DefaultHttpMethodRetryHandler(0, false);
        httpClient.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, retryhandler);
        httpClient.getHttpConnectionManager().getParams()
                .setConnectionTimeout(1000 * config.getConnectionTimeout());
        httpClient.getHttpConnectionManager().getParams().setSoTimeout(1000 * config.getSoTimeout());
        method.getParams().setSoTimeout(1000 * config.getSoTimeout());
        httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("ping: done. code=" + method.getStatusCode() + " - " + method.getStatusText());
        }
        lastStatusCode = method.getStatusCode();
        lastResponseEncoding = null;
        if (method.getStatusCode() == HttpServletResponse.SC_OK) {
            final Header contentEncoding = method.getResponseHeader("Content-Encoding");
            if (contentEncoding != null && contentEncoding.getValue() != null
                    && contentEncoding.getValue().contains("gzip")) {
                lastResponseEncoding = "gzip";
            } else {
                lastResponseEncoding = "plaintext";
            }
            String responseBody = requestValidator.decodeMessage(method); // limiting to 16MB, should be way enough
            if (logger.isDebugEnabled()) {
                logger.debug("ping: response body=" + responseBody);
            }
            if (responseBody != null && responseBody.length() > 0) {
                Announcement inheritedAnnouncement = Announcement.fromJSON(responseBody);
                final long backoffInterval = inheritedAnnouncement.getBackoffInterval();
                if (backoffInterval > 0) {
                    // then reset the backoffPeriodEnd:

                    /* minus 1 sec to avoid slipping the interval by a few millis */
                    this.backoffPeriodEnd = System.currentTimeMillis() + (1000 * backoffInterval) - 1000;
                    logger.debug("ping: servlet instructed to backoff: backoffInterval=" + backoffInterval
                            + ", resulting in period end of " + new Date(backoffPeriodEnd));
                } else {
                    logger.debug("ping: servlet did not instruct any backoff-ing at this stage");
                    this.backoffPeriodEnd = -1;
                }
                if (inheritedAnnouncement.isLoop()) {
                    if (logger.isDebugEnabled()) {
                        logger.debug(
                                "ping: connector response indicated a loop detected. not registering this announcement from "
                                        + inheritedAnnouncement.getOwnerId());
                    }
                    if (inheritedAnnouncement.getOwnerId().equals(clusterViewService.getSlingId())) {
                        // SLING-3316 : local-loop detected. Check config to see if we should stop this connector

                        if (config.isAutoStopLocalLoopEnabled()) {
                            inheritedAnnouncement = null; // results in connected -> false and representsloop -> true
                            autoStopped = true; // results in isAutoStopped -> true
                        }
                    }
                } else {
                    inheritedAnnouncement.setInherited(true);
                    if (announcementRegistry.registerAnnouncement(inheritedAnnouncement) == -1) {
                        if (logger.isDebugEnabled()) {
                            logger.debug(
                                    "ping: connector response is from an instance which I already see in my topology"
                                            + inheritedAnnouncement);
                        }
                        statusDetails = "receiving side is seeing me via another path (connector or cluster) already (loop)";
                        return;
                    }
                }
                resultingAnnouncement = inheritedAnnouncement;
                statusDetails = null;
            } else {
                statusDetails = "no response body received";
            }
        } else {
            statusDetails = "got HTTP Status-Code: " + lastStatusCode;
        }
        // SLING-2882 : reset suppressPingWarnings_ flag in success case
        suppressPingWarnings_ = false;
    } catch (URIException e) {
        logger.warn("ping: Got URIException: " + e + ", uri=" + uri);
        statusDetails = e.toString();
    } catch (IOException e) {
        // SLING-2882 : set/check the suppressPingWarnings_ flag
        if (suppressPingWarnings_) {
            if (logger.isDebugEnabled()) {
                logger.debug("ping: got IOException: " + e + ", uri=" + uri);
            }
        } else {
            suppressPingWarnings_ = true;
            logger.warn("ping: got IOException [suppressing further warns]: " + e + ", uri=" + uri);
        }
        statusDetails = e.toString();
    } catch (JSONException e) {
        logger.warn("ping: got JSONException: " + e);
        statusDetails = e.toString();
    } catch (RuntimeException re) {
        logger.warn("ping: got RuntimeException: " + re, re);
        statusDetails = re.toString();
    } finally {
        method.releaseConnection();
        lastInheritedAnnouncement = resultingAnnouncement;
        lastPingedAt = System.currentTimeMillis();
    }
}

From source file:org.apache.sling.discovery.impl.topology.connector.TopologyConnectorClient.java

/** Disconnect this connector **/
public void disconnect() {
    final String uri = connectorUrl.toString() + "." + clusterViewService.getSlingId() + ".json";
    if (logger.isDebugEnabled()) {
        logger.debug("disconnect: connectorUrl=" + connectorUrl + ", complete uri=" + uri);
    }//  w ww.  j  av a2 s .co  m

    if (lastInheritedAnnouncement != null) {
        announcementRegistry.unregisterAnnouncement(lastInheritedAnnouncement.getOwnerId());
    }

    HttpClient httpClient = new HttpClient();
    final DeleteMethod method = new DeleteMethod(uri);

    try {
        String userInfo = connectorUrl.getUserInfo();
        if (userInfo != null) {
            Credentials c = new UsernamePasswordCredentials(userInfo);
            httpClient.getState()
                    .setCredentials(new AuthScope(method.getURI().getHost(), method.getURI().getPort()), c);
        }

        requestValidator.trustMessage(method, null);
        httpClient.executeMethod(method);
        if (logger.isDebugEnabled()) {
            logger.debug("disconnect: done. code=" + method.getStatusCode() + " - " + method.getStatusText());
        }
        // ignoring the actual statuscode though as there's little we can
        // do about it after this point
    } catch (URIException e) {
        logger.warn("disconnect: Got URIException: " + e);
    } catch (IOException e) {
        logger.warn("disconnect: got IOException: " + e);
    } catch (RuntimeException re) {
        logger.error("disconnect: got RuntimeException: " + re, re);
    } finally {
        method.releaseConnection();
    }
}