Example usage for org.apache.commons.httpclient HttpState setCredentials

List of usage examples for org.apache.commons.httpclient HttpState setCredentials

Introduction

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

Prototype

public void setCredentials(String paramString1, String paramString2, Credentials paramCredentials)

Source Link

Usage

From source file:com.discursive.jccook.httpclient.BasicAuthExample.java

public static void main(String[] args) throws HttpException, IOException {
    // Configure Logging
    System.setProperty("org.apache.commons.logging.Log", "org.apache.commons.logging.impl.SimpleLog");
    System.setProperty("org.apache.commons.logging.simplelog.showdatetime", "true");
    System.setProperty("org.apache.commons.logging.simplelog.log.httpclient.wire", "debug");
    System.setProperty("org.apache.commons.logging.simplelog.log.org.apache.commons.httpclient", "debug");

    HttpClient client = new HttpClient();
    HttpState state = client.getState();
    HttpClientParams params = client.getParams();

    // Set credentials on the client
    Credentials credentials = new UsernamePasswordCredentials("testuser", "crazypass");
    state.setCredentials(null, null, credentials);
    params.setAuthenticationPreemptive(true);

    String url = "http://www.discursive.com/jccook/auth/";
    HttpMethod method = new GetMethod(url);

    client.executeMethod(method);/*from  w w  w.  j ava  2s .  c  o m*/
    String response = method.getResponseBodyAsString();

    System.out.println(response);
    method.releaseConnection();
}

From source file:org.apache.cactus.client.authentication.BasicAuthentication.java

/**
 * {@inheritDoc}/*from  w w  w . jav  a  2  s .com*/
 * @see Authentication#configure
 */
public void configure(HttpState theState, HttpMethod theMethod, WebRequest theRequest,
        Configuration theConfiguration) {
    theState.setAuthenticationPreemptive(true);
    theState.setCredentials(null, null, new UsernamePasswordCredentials(getName(), getPassword()));
    theMethod.setDoAuthentication(true);
}

From source file:org.apache.cocoon.generation.GenericProxyGenerator.java

/**
 * Get the request data, pass them on to the forwarder and return the result.
 *
 * TODO: much better header handling//from   www .j  av  a 2 s.co m
 * TODO: handle non XML and bodyless responses (probably needs a smarter Serializer,
 *            since some XML has to go through the pipeline anyway.
 *
 * @see org.apache.cocoon.generation.Generator#generate()
 */
public void generate() throws IOException, SAXException, ProcessingException {
    RequestForwardingHttpMethod method = new RequestForwardingHttpMethod(request, destination);

    // Build the forwarded connection
    HttpConnection conn = new HttpConnection(destination.getHost(), destination.getPort());
    HttpState state = new HttpState();
    state.setCredentials(null, destination.getHost(),
            new UsernamePasswordCredentials(destination.getUser(), destination.getPassword()));
    method.setPath(path);

    // Execute the method
    method.execute(state, conn);

    // Send the output to the client: set the status code...
    response.setStatus(method.getStatusCode());

    // ... retrieve the headers from the origin server and pass them on
    Header[] methodHeaders = method.getResponseHeaders();
    for (int i = 0; i < methodHeaders.length; i++) {
        // there is more than one DAV header
        if (methodHeaders[i].getName().equals("DAV")) {
            response.addHeader(methodHeaders[i].getName(), methodHeaders[i].getValue());
        } else if (methodHeaders[i].getName().equals("Content-Length")) {
            // drop the original Content-Length header. Don't ask me why but there
            // it's always one byte off
        } else {
            response.setHeader(methodHeaders[i].getName(), methodHeaders[i].getValue());
        }
    }

    // no HTTP keepalives here...
    response.setHeader("Connection", "close");

    // Parse the XML, if any
    if (method.getResponseHeader("Content-Type").getValue().startsWith("text/xml")) {
        InputStream stream = method.getResponseBodyAsStream();
        parser.parse(new InputSource(stream), this.contentHandler, this.lexicalHandler);
    } else {
        // Just send a dummy XML
        this.contentHandler.startDocument();
        this.contentHandler.startElement("", "no-xml-content", "no-xml-content", XMLUtils.EMPTY_ATTRIBUTES);
        this.contentHandler.endElement("", "no-xml-content", "no-xml-content");
        this.contentHandler.endDocument();
    }

    // again, no keepalive here.
    conn.close();
}

From source file:org.apache.webdav.lib.NotificationListener.java

/**
 * Registers a Subscriber with the remote server. 
 * //  ww w  . j a  v  a2 s .c  o  m
 * @param method the "notification type", determines for what events do you
 *               want do subscribe. one of  "Update", "Update/newmember",
 *               "Delete", "Move".
 * @param uri the resource for that you subscribe
 * @param depth the depth of the collection tree that you want to observe
 * @param lifetime the duration for that you want to observe (in seconds)
 * @param notificationDelay the time the server waits before it sends a notify
 *                          message to the host provided in the constructor
 *                          (in seconds)
 * @param listener the Subscriber that is called on incomming notifications
 * @param credentials credentials for authentication on the server observed
 * @return boolean true if subscription succeeded, false if subscription failed
 *
 * @see WebdavResource#subscribeMethod
 * @see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/e2k3/e2k3/_webdav_subscribe.asp
 */
public boolean subscribe(String method, String uri, int depth, int lifetime, int notificationDelay,
        Subscriber listener, Credentials credentials) {
    SubscribeMethod subscribeMethod = new SubscribeMethod(repositoryDomain + uri);
    subscribeMethod.addRequestHeader(SubscribeMethod.H_NOTIFICATION_TYPE, method);
    if (udp) {
        subscribeMethod.addRequestHeader(SubscribeMethod.H_CALL_BACK,
                "httpu://" + notificationHost + ":" + notificationPort);
    } else {
        subscribeMethod.addRequestHeader(SubscribeMethod.H_CALL_BACK,
                "http://" + notificationHost + ":" + notificationPort);
    }
    subscribeMethod.addRequestHeader(SubscribeMethod.H_NOTIFICATION_DELAY, String.valueOf(notificationDelay));
    subscribeMethod.addRequestHeader(SubscribeMethod.H_SUBSCRIPTION_LIFETIME, String.valueOf(lifetime));
    subscribeMethod.addRequestHeader(SubscribeMethod.H_DEPTH,
            ((depth == DepthSupport.DEPTH_INFINITY) ? "infinity" : String.valueOf(depth)));
    try {
        subscribeMethod.setDoAuthentication(true);
        HttpState httpState = new HttpState();
        httpState.setCredentials(null, repositoryHost, credentials);
        HttpConnection httpConnection = new HttpConnection(repositoryHost, repositoryPort, protocol);
        httpConnection.setConnectionTimeout(CONNECTION_TIMEOUT);
        int state = subscribeMethod.execute(httpState, httpConnection);
        if (state == HttpStatus.SC_OK) {
            String subscriptionId = subscribeMethod.getResponseHeader(SubscribeMethod.H_SUBSCRIPTION_ID)
                    .getValue();
            logger.log(Level.INFO, "Received subscription id=" + subscriptionId + ", listener: " + listener);
            int id = Integer.valueOf(subscriptionId).intValue();
            synchronized (subscribers) {
                subscribers.add(new Subscription(id, uri, listener));
            }
            if (subscribersAsString == null) {
                subscribersAsString = String.valueOf(id);
            } else {
                subscribersAsString = subscribersAsString + ", " + String.valueOf(id);
            }
            return true;
        } else {
            logger.log(Level.SEVERE, "Subscription for uri='" + uri + "' failed. State: " + state);
        }
    } catch (IOException e) {
        logger.log(Level.SEVERE, "Subscription of listener '" + listener + "' failed!", e);
    }
    return false;
}

From source file:org.apache.webdav.lib.NotificationListener.java

public boolean unsubscribe(String uri, Subscriber listener, Credentials credentials) {
    UnsubscribeMethod unsubscribeMethod = new UnsubscribeMethod(repositoryDomain + uri);
    synchronized (subscribers) {
        for (Iterator i = subscribers.iterator(); i.hasNext();) {
            Subscription subscription = (Subscription) i.next();
            if (subscription.getSubscriber().equals(listener)) {
                String id = String.valueOf(subscription.getId());
                unsubscribeMethod.addRequestHeader(UnsubscribeMethod.H_SUBSCRIPTION_ID, id);
                try {
                    unsubscribeMethod.setDoAuthentication(true);
                    HttpState httpState = new HttpState();
                    httpState.setCredentials(null, repositoryHost, credentials);
                    HttpConnection httpConnection = new HttpConnection(repositoryHost, repositoryPort,
                            protocol);//from w  ww  .  j av  a2 s  .c om
                    httpConnection.setConnectionTimeout(CONNECTION_TIMEOUT);
                    int state = unsubscribeMethod.execute(httpState, httpConnection);
                    if (state == HttpStatus.SC_OK) {
                        i.remove();
                        return true;
                    } else {
                        logger.log(Level.SEVERE, "Unsubscription failed. State: " + state);
                    }
                } catch (IOException e) {
                    logger.log(Level.SEVERE, "Unsubscription of listener '" + listener + "' failed!", e);
                }
            }
        }
    }
    logger.log(Level.SEVERE, "Listener not unsubscribed!");
    return false;
}

From source file:org.apache.webdav.lib.NotificationListener.java

protected void fireEvent(EventMethod eventMethod, Credentials credentials) throws IOException {
    eventMethod.setDoAuthentication(true);
    HttpState httpState = new HttpState();
    httpState.setCredentials(null, repositoryHost, credentials);
    int state = eventMethod.execute(httpState, new HttpConnection(repositoryHost, repositoryPort, protocol));
    if (state == HttpStatus.SC_OK) {
    } else {//from w w  w .j  ava 2  s.  c om
        logger.log(Level.SEVERE, "Event failed. State: " + state);
    }
}

From source file:org.apache.webdav.lib.NotificationListener.java

protected void poll(String notifiedSubscribers) {
    StringBuffer registeredSubscribers = new StringBuffer(256);
    StringTokenizer tokenizer = new StringTokenizer(notifiedSubscribers, ",");
    boolean first = true;
    while (tokenizer.hasMoreTokens()) {
        String subscriber = tokenizer.nextToken().trim();
        if (isRegistered(Integer.valueOf(subscriber).intValue())) {
            if (!first)
                registeredSubscribers.append(',');
            registeredSubscribers.append(subscriber);
            first = false;//  w  w w .  j  a  va2 s . co  m
        }
    }
    if (!first) {
        String pollSubscribers = registeredSubscribers.toString();
        logger.log(Level.INFO, "Poll for subscribers: " + pollSubscribers);
        PollMethod pollMethod = new PollMethod(repositoryDomain + "/");
        pollMethod.addRequestHeader(SubscribeMethod.H_SUBSCRIPTION_ID, pollSubscribers);
        try {
            pollMethod.setDoAuthentication(true);
            HttpState httpState = new HttpState();
            httpState.setCredentials(null, repositoryHost, credentials);
            HttpConnection httpConnection = new HttpConnection(repositoryHost, repositoryPort, protocol);
            httpConnection.setConnectionTimeout(CONNECTION_TIMEOUT);
            int state = pollMethod.execute(httpState, httpConnection);
            if (state == HttpStatus.SC_MULTI_STATUS) {
                List events = pollMethod.getEvents();
                for (Iterator i = events.iterator(); i.hasNext();) {
                    Event event = (Event) i.next();
                    fireEvent(event.getId(), event.getInformation());
                }
            } else {
                logger.log(Level.SEVERE, "Poll failed. State: " + state);
            }
        } catch (IOException e) {
            logger.log(Level.SEVERE, "Poll for subscribers '" + subscribers + "' failed!");
        }
    }
}

From source file:org.apache.webdav.lib.WebdavSession.java

/**
 * Get a <code>HttpClient</code> instance.
 * This method returns a new client instance, when reset is true.
 *
 * @param httpURL The http URL to connect.  only used the authority part.
 * @param reset The reset flag to represent whether the saved information
 *              is used or not./*from   w ww . j a v a  2s. c  o m*/
 * @return An instance of <code>HttpClient</code>.
 * @exception IOException
 */
public HttpClient getSessionInstance(HttpURL httpURL, boolean reset) throws IOException {

    if (reset || client == null) {
        client = new HttpClient();
        // Set a state which allows lock tracking
        client.setState(new WebdavState());
        HostConfiguration hostConfig = client.getHostConfiguration();
        hostConfig.setHost(httpURL);
        if (proxyHost != null && proxyPort > 0)
            hostConfig.setProxy(proxyHost, proxyPort);

        if (hostCredentials == null) {
            String userName = httpURL.getUser();
            if (userName != null && userName.length() > 0) {
                hostCredentials = new UsernamePasswordCredentials(userName, httpURL.getPassword());
            }
        }

        if (hostCredentials != null) {
            HttpState clientState = client.getState();
            clientState.setCredentials(null, httpURL.getHost(), hostCredentials);
            clientState.setAuthenticationPreemptive(true);
        }

        if (proxyCredentials != null) {
            client.getState().setProxyCredentials(null, proxyHost, proxyCredentials);
        }
    }

    return client;
}

From source file:org.jboss.test.security.test.SubjectContextUnitTestCase.java

public void testUserMethodViaServlet() throws Exception {
    log.debug("+++ testUserMethodViaServlet()");
    SecurityAssociation.clear();//from   w ww  .j  a  v a  2 s. c o m

    Principal callerIdentity = new SimplePrincipal("jduke");
    Principal runAsIdentity = new SimplePrincipal("runAsUser");
    HashSet expectedCallerRoles = new HashSet();
    expectedCallerRoles.add("groupMemberCaller");
    expectedCallerRoles.add("userCaller");
    expectedCallerRoles.add("allAuthCaller");
    expectedCallerRoles.add("webUser");
    HashSet expectedRunAsRoles = new HashSet();
    expectedRunAsRoles.add("identitySubstitutionCaller");
    expectedRunAsRoles.add("extraRunAsRole");
    CallerInfo info = new CallerInfo(callerIdentity, runAsIdentity, expectedCallerRoles, expectedRunAsRoles);

    String baseURL = HttpUtils.getBaseURL("jduke", "theduke");
    PostMethod formPost = new PostMethod(baseURL + "subject-context/restricted/RunAsServlet");
    formPost.setDoAuthentication(true);
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject("userMethod");
    oos.writeObject(info);
    oos.close();
    log.info("post content length: " + baos.toByteArray().length);
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    formPost.setRequestBody(bais);
    String host = formPost.getHostConfiguration().getHost();
    HttpClient httpConn = new HttpClient();
    HttpState state = httpConn.getState();
    state.setAuthenticationPreemptive(true);
    UsernamePasswordCredentials upc = new UsernamePasswordCredentials("jduke", "theduke");
    state.setCredentials("JBossTest Servlets", host, upc);

    int responseCode = httpConn.executeMethod(formPost);
    assertTrue("POST OK(" + responseCode + ")", responseCode == HttpURLConnection.HTTP_OK);
}

From source file:org.pengyou.client.lib.DavSession.java

/**
 * Get a <code>HttpClient</code> instance.
 * This method returns a new client instance, when reset is true.
 *
 * @param reset The reset flag to represent whether the saved information
 *              is used or not./*from w  ww .  j a  v a 2s. c  o  m*/
 * @return An instance of <code>HttpClient</code>.
 * @exception IOException
 */
public HttpClient getSessionInstance(boolean reset) throws IOException {

    if (reset || client == null) {
        HttpURL httpURL = context.getHttpURL();
        client = new HttpClient();
        // Set a state which allows lock tracking
        client.setState(new WebdavState());
        HostConfiguration hostConfig = client.getHostConfiguration();
        hostConfig.setHost(httpURL);
        if (context.getProxyHost() != null && context.getProxyPort() > 0)
            hostConfig.setProxy(context.getProxyHost(), context.getProxyPort());

        if (hostCredentials == null) {
            String userName = httpURL.getUser();
            if (userName != null && userName.length() > 0) {
                hostCredentials = new UsernamePasswordCredentials(userName, httpURL.getPassword());
            }
        }

        if (hostCredentials != null) {
            HttpState clientState = client.getState();
            clientState.setCredentials(null, httpURL.getHost(), hostCredentials);
            clientState.setAuthenticationPreemptive(true);
        }

        if (proxyCredentials != null) {
            client.getState().setProxyCredentials(null, context.getProxyHost(), proxyCredentials);
        }
    }

    return client;
}