Example usage for org.apache.commons.httpclient HttpURL getPassword

List of usage examples for org.apache.commons.httpclient HttpURL getPassword

Introduction

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

Prototype

public String getPassword() throws URIException 

Source Link

Usage

From source file:com.zimbra.common.util.HttpUtil.java

/** Strips any userinfo (username/password) data from the passed-in URL
 *  and returns the result. *//*from  ww  w  .j a  va2 s .c  om*/
public static String sanitizeURL(String url) {
    if (url != null && url.indexOf('@') != -1) {
        try {
            HttpURL httpurl = (url.indexOf("https:") == 0) ? new HttpsURL(url) : new HttpURL(url);
            if (httpurl.getPassword() != null) {
                httpurl.setPassword("");
                return httpurl.toString();
            }
        } catch (org.apache.commons.httpclient.URIException urie) {
        }
    }
    return url;
}

From source file:com.zimbra.cs.service.FeedManager.java

private static RemoteDataInfo retrieveRemoteData(String url, Folder.SyncData fsd)
        throws ServiceException, HttpException, IOException {
    assert !Strings.isNullOrEmpty(url);

    HttpClient client = ZimbraHttpConnectionManager.getExternalHttpConnMgr().newHttpClient();
    HttpProxyUtil.configureProxy(client);

    // cannot set connection timeout because it'll affect all HttpClients associated with the conn mgr.
    // see comments in ZimbraHttpConnectionManager
    // client.setConnectionTimeout(10000);

    HttpMethodParams params = new HttpMethodParams();
    params.setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, MimeConstants.P_CHARSET_UTF8);
    params.setSoTimeout(60000);//from w  w  w .  j  a v a  2 s .c o  m

    GetMethod get = null;
    BufferedInputStream content = null;
    long lastModified = 0;
    String expectedCharset = MimeConstants.P_CHARSET_UTF8;
    int redirects = 0;
    int statusCode = HttpServletResponse.SC_NOT_FOUND;
    try {
        do {
            String lcurl = url.toLowerCase();
            if (lcurl.startsWith("webcal:")) {
                url = "http:" + url.substring(7);
            } else if (lcurl.startsWith("feed:")) {
                url = "http:" + url.substring(5);
            } else if (!lcurl.startsWith("http:") && !lcurl.startsWith("https:")) {
                throw ServiceException.INVALID_REQUEST("url must begin with http: or https:", null);
            }

            // username and password are encoded in the URL as http://user:pass@host/...
            if (url.indexOf('@') != -1) {
                HttpURL httpurl = lcurl.startsWith("https:") ? new HttpsURL(url) : new HttpURL(url);
                if (httpurl.getUser() != null) {
                    String user = httpurl.getUser();
                    if (user.indexOf('%') != -1) {
                        try {
                            user = URLDecoder.decode(user, "UTF-8");
                        } catch (OutOfMemoryError e) {
                            Zimbra.halt("out of memory", e);
                        } catch (Throwable t) {
                        }
                    }
                    UsernamePasswordCredentials creds = new UsernamePasswordCredentials(user,
                            httpurl.getPassword());
                    client.getParams().setAuthenticationPreemptive(true);
                    client.getState().setCredentials(AuthScope.ANY, creds);
                }
            }

            try {
                get = new GetMethod(url);
            } catch (OutOfMemoryError e) {
                Zimbra.halt("out of memory", e);
                return null;
            } catch (Throwable t) {
                throw ServiceException.INVALID_REQUEST("invalid url for feed: " + url, t);
            }
            get.setParams(params);
            get.setFollowRedirects(true);
            get.setDoAuthentication(true);
            get.addRequestHeader("User-Agent", HTTP_USER_AGENT);
            get.addRequestHeader("Accept", HTTP_ACCEPT);
            if (fsd != null && fsd.getLastSyncDate() > 0) {
                String lastSyncAt = org.apache.commons.httpclient.util.DateUtil
                        .formatDate(new Date(fsd.getLastSyncDate()));
                get.addRequestHeader("If-Modified-Since", lastSyncAt);
            }
            HttpClientUtil.executeMethod(client, get);

            Header locationHeader = get.getResponseHeader("location");
            if (locationHeader != null) {
                // update our target URL and loop again to do another HTTP GET
                url = locationHeader.getValue();
                get.releaseConnection();
            } else {
                statusCode = get.getStatusCode();
                if (statusCode == HttpServletResponse.SC_OK) {
                    Header contentEncoding = get.getResponseHeader("Content-Encoding");
                    InputStream respInputStream = get.getResponseBodyAsStream();
                    if (contentEncoding != null) {
                        if (contentEncoding.getValue().indexOf("gzip") != -1) {
                            respInputStream = new GZIPInputStream(respInputStream);
                        }
                    }
                    content = new BufferedInputStream(respInputStream);
                    expectedCharset = get.getResponseCharSet();

                    Header lastModHdr = get.getResponseHeader("Last-Modified");
                    if (lastModHdr == null) {
                        lastModHdr = get.getResponseHeader("Date");
                    }
                    if (lastModHdr != null) {
                        try {
                            Date d = org.apache.commons.httpclient.util.DateUtil
                                    .parseDate(lastModHdr.getValue());
                            lastModified = d.getTime();
                        } catch (DateParseException e) {
                            ZimbraLog.misc.warn(
                                    "unable to parse Last-Modified/Date header: " + lastModHdr.getValue(), e);
                            lastModified = System.currentTimeMillis();
                        }
                    } else {
                        lastModified = System.currentTimeMillis();
                    }
                } else if (statusCode == HttpServletResponse.SC_NOT_MODIFIED) {
                    ZimbraLog.misc.debug("Remote data at " + url + " not modified since last sync");
                    return new RemoteDataInfo(statusCode, redirects, null, expectedCharset, lastModified);
                } else {
                    throw ServiceException.RESOURCE_UNREACHABLE(get.getStatusLine().toString(), null);
                }
                break;
            }
        } while (++redirects <= MAX_REDIRECTS);
    } catch (ServiceException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (HttpException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    } catch (IOException ex) {
        if (get != null) {
            get.releaseConnection();
        }
        throw ex;
    }
    RemoteDataInfo rdi = new RemoteDataInfo(statusCode, redirects, content, expectedCharset, lastModified);
    rdi.setGetMethod(get);
    return rdi;
}

From source file:com.idega.slide.business.IWSlideServiceBean.java

@SuppressWarnings("deprecation")
private HttpClient getHttpClient(HttpURL url, UsernamePasswordCredentials credentials) throws Exception {
    HttpSession currentSession = getCurrentSession();

    HttpState state = new WebdavState();
    AuthScope authScope = new AuthScope(url.getHost(), url.getPort());
    state.setCredentials(authScope, credentials);
    if (currentSession != null) {
        IWTimestamp iwExpires = new IWTimestamp(System.currentTimeMillis());
        iwExpires.setMinute(iwExpires.getMinute() + 30);
        Date expires = new Date(iwExpires.getTimestamp().getTime());

        boolean secure = url instanceof HttpsURL;

        Cookie cookie = new Cookie(url.getHost(), CoreConstants.PARAMETER_SESSION_ID, currentSession.getId(),
                CoreConstants.SLASH, expires, secure);
        state.addCookie(cookie);/*from   ww  w .j  a  v a2  s.co m*/
    }

    HttpClient client = new HttpClient(new MultiThreadedHttpConnectionManager());
    client.setState(state);

    HostConfiguration hostConfig = client.getHostConfiguration();
    hostConfig.setHost(url);

    Credentials hostCredentials = null;

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

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

    return client;
}

From source file:org.apache.cocoon.components.source.impl.WebDAVSource.java

/**
 * Default constructor./*from  w  w  w. ja  v a  2s . c  o  m*/
 */
private WebDAVSource(HttpURL url, String protocol) throws URIException {
    this.protocol = protocol;
    this.url = url;

    String qs = url.getQuery();
    if (qs != null) {
        final SourceParameters sp = new SourceParameters(qs);

        // parse optional start depth and start action qs parameters
        this.depth = sp.getParameterAsInteger("cocoon:webdav-depth", DepthSupport.DEPTH_1);
        this.action = sp.getParameterAsInteger("cocoon:webdav-action", WebdavResource.NOACTION);

        // [UH] FIXME: Why this alternative way of passing in credentials?
        String principal = url.getUser();
        String password = url.getPassword();
        if (principal == null || password == null) {
            principal = sp.getParameter("cocoon:webdav-principal", principal);
            password = sp.getParameter("cocoon:webdav-password", password);
            if (principal != null) {
                url.setUser(principal);
                url.setPassword(password);
            }
        }

        sp.removeParameter("cocoon:webdav-depth");
        sp.removeParameter("cocoon:webdav-action");
        sp.removeParameter("cocoon:webdav-principal");
        sp.removeParameter("cocoon:webdav-password");

        // set the qs without WebdavSource specific parameters
        url.setQuery(sp.getQueryString());
    }
}

From source file:org.apache.cocoon.transformation.DASLTransformer.java

protected void performSearchMethod(String query) throws SAXException {
    OptionsMethod optionsMethod = null;/*  w  w w .j a  va  2s  .c  o m*/
    SearchMethod searchMethod = null;
    try {
        DOMStreamer propertyStreamer = new DOMStreamer(this.xmlConsumer);
        optionsMethod = new OptionsMethod(this.targetUrl);
        searchMethod = new SearchMethod(this.targetUrl, query);
        HttpURL url = new HttpURL(this.targetUrl);
        HttpState state = new HttpState();
        state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword()));
        HttpConnection conn = new HttpConnection(url.getHost(), url.getPort());

        // eventcaching stuff
        SourceValidity extraValidity = makeWebdavEventValidity(url);
        if (extraValidity != null && m_validity != null)
            m_validity.add(extraValidity);
        // end eventcaching stuff

        WebdavResource resource = new WebdavResource(new HttpURL(this.targetUrl));
        if (!resource.exists()) {
            throw new SAXException("The WebDAV resource don't exist");
        }
        optionsMethod.execute(state, conn);
        if (!optionsMethod.isAllowed("SEARCH")) {
            throw new SAXException("The server doesn't support the SEARCH method");
        }
        int httpstatus = searchMethod.execute(state, conn);

        this.contentHandler.startElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG,
                XMLUtils.EMPTY_ATTRIBUTES);

        // something might have gone wrong, report it
        // 207 = multistatus webdav response
        if (httpstatus != 207) {

            this.contentHandler.startElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG,
                    XMLUtils.EMPTY_ATTRIBUTES);

            // dump whatever the server said
            propertyStreamer.stream(searchMethod.getResponseDocument());

            this.contentHandler.endElement(DASL_QUERY_NS, ERROR_ROOT_TAG, PREFIX + ":" + ERROR_ROOT_TAG);

        } else {
            // show results

            Enumeration enumeration = searchMethod.getAllResponseURLs();

            while (enumeration.hasMoreElements()) {
                String path = (String) enumeration.nextElement();
                Enumeration properties = searchMethod.getResponseProperties(path);
                AttributesImpl attr = new AttributesImpl();
                attr.addAttribute(DASL_QUERY_NS, PATH_NODE_NAME, PREFIX + ":" + PATH_NODE_NAME, "CDATA", path);

                this.contentHandler.startElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME, attr);
                while (properties.hasMoreElements()) {
                    BaseProperty metadata = (BaseProperty) properties.nextElement();
                    Element propertyElement = metadata.getElement();
                    propertyStreamer.stream(propertyElement);
                }

                this.contentHandler.endElement(DASL_QUERY_NS, RESOURCE_NODE_NAME,
                        PREFIX + ":" + RESOURCE_NODE_NAME);
            }
        }

        this.contentHandler.endElement(DASL_QUERY_NS, RESULT_ROOT_TAG, PREFIX + ":" + RESULT_ROOT_TAG);
    } catch (SAXException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (HttpException e1) {
        this.getLogger().error("Unable to contact Webdav server", e1);
        throw new SAXException("Unable to connect with server: ", e1);
    } catch (IOException e2) {
        throw new SAXException("Unable to connect with server: ", e2);
    } catch (NullPointerException e) {
        throw new SAXException("Unable to fetch the query data:", e);
    } catch (Exception e) {
        throw new SAXException("Generic Error:", e);
    } finally {
        // cleanup
        if (searchMethod != null)
            searchMethod.releaseConnection();
        if (optionsMethod != null)
            optionsMethod.releaseConnection();
    }
}

From source file:org.apache.cocoon.transformation.WebDAVTransformer.java

public void endElement(String uri, String name, String raw) throws SAXException {
    if (name.equals(REQUEST_TAG) && uri.equals(NS_URI)) {

        try {//from  w ww. j a v  a  2  s . c  o m
            HttpURL url = new HttpURL(m_target);
            if (url.getUser() != null && !"".equals(url.getUser())) {
                m_state.setCredentials(null, new UsernamePasswordCredentials(url.getUser(), url.getPassword()));
            }
            m_target = url.getURI();

            if (m_validity != null) {
                m_validity.add(makeWebdavEventValidity(url));
            }

        } catch (Exception e) {
            //ignore
        }

        // create method
        WebDAVRequestMethod method = new WebDAVRequestMethod(m_target, m_method);

        try {
            // add request headers
            Iterator headers = m_headers.entrySet().iterator();
            while (headers.hasNext()) {
                Map.Entry header = (Map.Entry) headers.next();
                method.addRequestHeader((String) header.getKey(), (String) header.getValue());
            }

            Properties props = XMLUtils.createPropertiesForXML(false);
            props.put(OutputKeys.ENCODING, "ISO-8859-1");
            String body = XMLUtils.serializeNode(m_requestdocument, props);
            // set request body
            method.setRequestBody(body.getBytes("ISO-8859-1"));

            // execute the request
            executeRequest(method);
        } catch (ProcessingException e) {
            if (getLogger().isErrorEnabled()) {
                getLogger().debug("Couldn't read request from sax stream", e);
            }
            throw new SAXException("Couldn't read request from sax stream", e);
        } catch (UnsupportedEncodingException e) {
            if (getLogger().isErrorEnabled()) {
                getLogger().debug("ISO-8859-1 encoding not present", e);
            }
            throw new SAXException("ISO-8859-1 encoding not present", e);
        } finally {
            method.releaseConnection();
            m_headers = null;
        }
    } else if (name.equals(HEADER_TAG) && uri.equals(NS_URI)) {
        // dont do anything
    } else if (name.equals(BODY_TAG) && uri.equals(NS_URI)) {
        m_requestdocument = super.endRecording();
    } else {
        super.endElement(uri, name, raw);
    }
}

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 a2s .  co 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.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./*  w  w  w.jav a2 s  . c om*/
 * @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;
}