Example usage for org.apache.commons.httpclient URI getEscapedQuery

List of usage examples for org.apache.commons.httpclient URI getEscapedQuery

Introduction

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

Prototype

public String getEscapedQuery() 

Source Link

Document

Get the escaped query.

Usage

From source file:com.eviware.soapui.impl.support.HttpUtils.java

public static java.net.URI createUri(URI uri) throws URISyntaxException, URIException {
    return createUri(uri.getScheme(), uri.getUserinfo(), uri.getHost(), uri.getPort(), uri.getEscapedPath(),
            uri.getEscapedQuery(), uri.getEscapedFragment());
}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * Redirect to SP SAMLDS return url with entityID of the IdP
 * //from w  w  w.ja  v  a 2s  .  c o m
 * @param spResponseURI
 * @param idp
 * @return
 * @throws NullPointerException
 * @throws ServiceException
 * @throws IOException
 * @throws HttpException
 * @throws RemoteException
 */
private URI processSPSAML2DS(URI spResponseURI, IdentityProvider idp)
        throws NullPointerException, ServiceException, HttpException, IOException, RemoteException {
    String entityID = idp.getEntityID();
    if (entityID == null) {
        String error = "IdentityProvider " + idp.getId() + " doesn't have a SAML2 entityID";
        LOG.error(error);
        throw new ServiceException(error);
    }
    String returnURL = null;
    String query = spResponseURI.getEscapedQuery();
    LOG.debug("SAMLDS query: " + query);
    for (String param : query.split("&")) {
        if (param.startsWith("return=")) {
            returnURL = param.substring("return=".length());
            try {
                returnURL = URLDecoder.decode(returnURL, "UTF-8");
            } catch (UnsupportedEncodingException e) {
                // ignored, not possible
            }
        }
    }
    if (returnURL == null) {
        throw new ServiceException("SAML2 DS return URL not found in " + spResponseURI);
    }

    // add the IdP SAML2 entityID param
    returnURL += "&entityID=" + entityID;
    LOG.debug("return URL to SAMLDS: " + returnURL);

    GetMethod getSPSAML2DSMethod = new GetMethod(returnURL);
    getSPSAML2DSMethod.setFollowRedirects(false);
    int spSAML2DSStatus = executeMethod(getSPSAML2DSMethod);
    String spSAML2DSStatusLine = getSPSAML2DSMethod.getStatusLine().toString();
    LOG.debug("spSAML2DSStatusLine=" + spSAML2DSStatusLine);
    URI saml2DSResponseURI = getSPSAML2DSMethod.getURI();
    if (spSAML2DSStatus == 302) {
        Header locationHeader = getSPSAML2DSMethod.getResponseHeader("Location");
        String location = locationHeader.getValue();
        LOG.debug("Redirect location=" + location);
        saml2DSResponseURI = new URI(location, true);
    }

    LOG.trace("getSPSAML2DSMethod.releaseConnection()");
    getSPSAML2DSMethod.releaseConnection();

    if (spSAML2DSStatus != 302) {
        throw new RemoteException("Unexpected SAML2 DS response: " + spSAML2DSStatusLine + " ("
                + saml2DSResponseURI + ") for " + returnURL);
    }

    return saml2DSResponseURI;

}

From source file:org.glite.slcs.shibclient.ShibbolethClient.java

/**
 * @param idp//from   w ww .  ja  v  a  2  s .c  o  m
 * @param query
 * @throws URIException
 * @throws HttpException
 * @throws IOException
 * @throws AuthException
 * @throws RemoteException
 * @throws ServiceException
 */
private URI processIdPSSO(IdentityProvider idp, URI spResponseURI)
        throws URIException, HttpException, IOException, AuthException, RemoteException, ServiceException {
    String idpSSOURL = idp.getUrl();
    LOG.debug("IdP SSO URL: " + idpSSOURL);
    String spResponseURL = spResponseURI.getEscapedURI();
    LOG.debug("spResponseURL=" + spResponseURL);
    // check if the spResponseURL is not already the IdP SSO url
    if (spResponseURL.startsWith(idpSSOURL)) {
        idpSSOURL = spResponseURL;
    } else {
        // if not, build it
        // BUG FIX: Shib SP 2.0 send the ?service=... in the query
        String query = spResponseURI.getEscapedQuery();
        LOG.debug("IdP SSO Query: " + query);
        if (query != null) {
            if (query.startsWith("service=")) {
                int i = query.indexOf("shire");
                if (i > 0) {
                    query = query.substring(i);
                    LOG.debug(
                            "IdP SSO Query contains the 'service=...' part, cutting up to 'shire=': " + query);
                } else {
                    LOG.error(
                            "IdP SSO Query contains the 'service=' parameter, but not the 'shire=' parameter: "
                                    + query);
                    throw new RemoteException(
                            "IdP SSO Query contains the 'service=' parameter, but not the 'shire=' parameter: "
                                    + query);
                }
            }
            // getIdpSSOMethod.setQueryString(query);
            idpSSOURL += "?" + query;
        }
        LOG.debug("IdP SSO URL (with query): " + idpSSOURL);
    }
    // create HttpMethod
    GetMethod getIdpSSOMethod = new GetMethod(idpSSOURL);

    URI idpSSOURI = getIdpSSOMethod.getURI();
    // set credential for basic or ntlm
    int authType = idp.getAuthType();
    LOG.debug("IdP authType: " + idp.getAuthTypeName());
    if (authType == IdentityProvider.SSO_AUTHTYPE_BASIC || authType == IdentityProvider.SSO_AUTHTYPE_NTLM) {
        // enable BASIC or NTLM authN
        AuthScope scope = new AuthScope(idpSSOURI.getHost(), idpSSOURI.getPort(), idp.getAuthRealm());
        LOG.info("Enable " + idp.getAuthTypeName() + " authentication: " + credentials_ + ", scope: " + scope);
        httpClient_.getState().setCredentials(scope, credentials_);
        getIdpSSOMethod.setDoAuthentication(true);
    }

    // execute the method
    LOG.info("GET IdpSSOMethod: " + idpSSOURI);
    int idpSSOResponseStatus = executeMethod(getIdpSSOMethod);
    String idpSSOResponseStatusLine = getIdpSSOMethod.getStatusLine().toString();
    LOG.debug(idpSSOResponseStatusLine);

    URI idpSSOResponseURI = getIdpSSOMethod.getURI();
    LOG.debug("idpSSOResponseURI=" + idpSSOResponseURI);
    String idpSSOResponseQuery = idpSSOResponseURI.getEscapedQuery();
    LOG.debug("idpSSOResponseQuery=" + idpSSOResponseQuery);

    // XXX
    dumpHttpClientCookies();

    LOG.debug("idpSSOResponseStatus=" + idpSSOResponseStatus);
    // BASIC or NTLM response handling
    if (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_BASIC
            || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_NTLM) {
        // !200 and same URL as before: if BASIC or NTLM failed on IdP

        LOG.debug("idpSSOURI=" + idpSSOURI);
        LOG.debug("idpSSOResponseURI=" + idpSSOResponseURI);

        if (idpSSOResponseStatus != 200 && idpSSOResponseURI.equals(idpSSOURI)) {

            LOG.trace("getIdpSSOMethod.releaseConnection()");
            getIdpSSOMethod.releaseConnection();

            LOG.error("BASIC or NTLM authentication was required for " + idpSSOURL);

            throw new AuthException(
                    idp.getAuthTypeName() + " authentication failed: " + idpSSOResponseStatusLine + " URL: "
                            + idpSSOResponseURI + " Credentials: " + this.credentials_);
        } else {
            // SAML/Artifact: idpSSOResponseURI is already SP login and the
            // XML <SLCSLoginResponse> is already there
            // XXX: resend to same IdP SSO page once again
            LOG.info("IdP BASIC or NTLM authN: resend again to the same IdP SSO URI: " + idpSSOURL);
            idpSSOResponseURI = new URI(idpSSOURL, false);
        }

    }
    // CAS sends 200 + Cookies and the login form directly
    else if (idpSSOResponseStatus == 200 && (idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_CAS
            || idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_FORM)) {
        LOG.debug("Process " + idp.getAuthTypeName() + " login form...");
        // process CAS login form
        InputStream idpLoginForm = getIdpSSOMethod.getResponseBodyAsStream();
        LOG.debug("idpSSOURI Query=" + idpSSOURI.getQuery());
        idpSSOResponseURI = processIdPLoginForm(idp, idpSSOResponseURI, idpSSOURI.getQuery(), idpLoginForm);
        LOG.debug(idp.getAuthTypeName() + " idpSSOResponseURI=" + idpSSOResponseURI);
    }
    // FIXME: ETHZ use a new PubCookie
    // PUBCOOKIE sends 200 + onload form with hidden fields to post
    else if (idpSSOResponseStatus == 200 && idp.getAuthType() == IdentityProvider.SSO_AUTHTYPE_PUBCOOKIE) {

        // parse <form> and extract hidden fields, then post
        PostMethod postPubcookieFormMethod = null;
        InputStream pubcookieFormStream = getIdpSSOMethod.getResponseBodyAsStream();
        Source source = new Source(pubcookieFormStream);
        List<Element> forms = source.findAllElements(Tag.FORM);
        for (Element form : forms) {
            String formAction = form.getAttributeValue("ACTION");
            LOG.debug("PubCookie form action=" + formAction);
            if (!idp.getAuthUrl().equalsIgnoreCase(formAction)) {
                // TODO: ERROR
                throw new RemoteException(
                        "form action: " + formAction + " doesn't match IdP authN url: " + idp.getAuthUrl());
            }
            // create PubCookie POST
            postPubcookieFormMethod = new PostMethod(formAction);

            // add all HIDDEN fields to POST
            List<FormControl> formControls = form.findFormControls();
            for (FormControl control : formControls) {
                FormControlType type = control.getFormControlType();
                if (type.equals(FormControlType.HIDDEN)) {
                    String name = control.getName();
                    Collection<String> values = control.getValues();
                    for (String value : values) {
                        LOG.debug("add hidden: " + name + "=" + value);
                        // add all hidden fields
                        postPubcookieFormMethod.addParameter(name, value);
                    }
                }
            }

        } // for all forms

        LOG.trace("getIdpSSOMethod.releaseConnection()");
        getIdpSSOMethod.releaseConnection();

        if (postPubcookieFormMethod == null) {
            // ERROR
            LOG.error("PubCookie form not found");
            throw new RemoteException("PubCookie form not found");
        }

        //
        LOG.debug("POST " + postPubcookieFormMethod.getURI());
        int postPubcookieFormStatus = executeMethod(postPubcookieFormMethod);
        LOG.debug(postPubcookieFormMethod.getStatusLine());

        // XXX
        dumpHttpClientCookies();

        // process pubcookie login form
        InputStream loginFormStream = postPubcookieFormMethod.getResponseBodyAsStream();
        idpSSOResponseURI = processIdPLoginForm(idp, idpSSOResponseURI, idpSSOURI.getQuery(), loginFormStream);
        LOG.debug("Pubcookie idpSSOResponseURI=" + idpSSOResponseURI);

        LOG.trace("postPubcookieFormMethod.releaseConnection()");
        postPubcookieFormMethod.releaseConnection();

    } else {
        // error handling
        InputStream htmlStream = getIdpSSOMethod.getResponseBodyAsStream();
        String htmlBody = inputStreamToString(htmlStream);
        LOG.error("Unexpected IdP SSO reponse: URL: " + idpSSOResponseURI + " Status: "
                + idpSSOResponseStatusLine + " AuthType: " + idp.getAuthTypeName() + " HTML:\n" + htmlBody);
        LOG.debug("getIdpSSOMethod.releaseConnection()");
        getIdpSSOMethod.releaseConnection();
        throw new RemoteException("Unexprected IdP SSO reponse: URL: " + idpSSOResponseURI + " Status: "
                + idpSSOResponseStatusLine + ". Please see the log file.");
    }

    LOG.debug("getIdpSSOMethod.releaseConnection()");
    getIdpSSOMethod.releaseConnection();

    return idpSSOResponseURI;

}

From source file:org.openlaszlo.data.HTTPDataSource.java

/**
 * @param since last modified time to use
 * @param req/*from   w w w.j a va2s  . c  o  m*/
 * @param url if null, ignored
 * @param redirCount number of redirs we've done
 */
public static HttpData getDataOnce(HttpServletRequest req, HttpServletResponse res, long since, String surl,
        int redirCount, int timeout)
        throws IOException, HttpException, DataSourceException, MalformedURLException {

    HttpMethodBase request = null;
    HostConfiguration hcfg = new HostConfiguration();

    /*
      [todo hqm 2006-02-01] Anyone know why this code was here? It is setting
      the mime type to something which just confuses the DHTML parser.
              
      if (res != null) {
    res.setContentType("application/x-www-form-urlencoded;charset=UTF-8");
    }
    */

    try {

        // TODO: [2002-01-09 bloch] cope with cache-control
        // response headers (no-store, no-cache, must-revalidate, 
        // proxy-revalidate).

        if (surl == null) {
            surl = getURL(req);
        }
        if (surl == null || surl.equals("")) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="url is empty or null"
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                            "051018-312"));
        }

        String reqType = "";
        String headers = "";

        if (req != null) {
            reqType = req.getParameter("reqtype");
            headers = req.getParameter("headers");
        }

        boolean isPost = false;
        mLogger.debug("reqtype = " + reqType);

        if (reqType != null && reqType.equals("POST")) {
            request = new LZPostMethod();
            request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=UTF-8");
            isPost = true;
            mLogger.debug("setting POST req method");
        } else if (reqType != null && reqType.equals("PUT")) {
            request = new LZPutMethod();
            // todo [hqm 2007] treat PUT like POST? 
            isPost = true;
            mLogger.debug("setting PUT req method");
        } else if (reqType != null && reqType.equals("DELETE")) {
            request = new LZDeleteMethod();
            mLogger.debug("setting DELETE req method");
        } else {
            mLogger.debug("setting GET (default) req method");
            request = new LZGetMethod();
        }

        request.getParams().setVersion(mUseHttp11 ? HttpVersion.HTTP_1_1 : HttpVersion.HTTP_1_0);

        // Proxy the request headers
        if (req != null) {
            LZHttpUtils.proxyRequestHeaders(req, request);
        }

        // Set headers from query string
        if (headers != null && headers.length() > 0) {
            StringTokenizer st = new StringTokenizer(headers, "\n");
            while (st.hasMoreTokens()) {
                String h = st.nextToken();
                int i = h.indexOf(":");
                if (i > -1) {
                    String n = h.substring(0, i);
                    String v = h.substring(i + 2, h.length());
                    request.setRequestHeader(n, v);
                    mLogger.debug(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes="setting header " + p[0] + "=" + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-359", new Object[] { n, v }));
                }
            }
        }

        mLogger.debug("Parsing url");
        URI uri = LZHttpUtils.newURI(surl);
        try {
            hcfg.setHost(uri);
        } catch (Exception e) {
            throw new MalformedURLException(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="can't form uri from " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-376",
                            new Object[] { surl }));
        }

        // This gets us the url-encoded (escaped) path and query string
        String path = uri.getEscapedPath();
        String query = uri.getEscapedQuery();
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded path:  " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-389",
                        new Object[] { path }));
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="encoded query: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-397",
                        new Object[] { query }));

        // This call takes a decoded (unescaped) path
        request.setPath(path);

        boolean hasQuery = (query != null && query.length() > 0);

        String rawcontent = null;
        // Newer rawpost protocol puts lzpostbody as a separate
        // top level query arg in the request.
        rawcontent = req.getParameter("lzpostbody");

        if (isPost) {
            // Older rawpost protocol put the "lzpostbody" arg
            // embedded in the "url" args's query args
            if (rawcontent == null && hasQuery) {
                rawcontent = findQueryArg("lzpostbody", query);
            }
            if (rawcontent != null) {
                // Get the unescaped query string
                ((EntityEnclosingMethod) request).setRequestEntity(new StringRequestEntity(rawcontent));
            } else if (hasQuery) {
                StringTokenizer st = new StringTokenizer(query, "&");
                while (st.hasMoreTokens()) {
                    String it = st.nextToken();
                    int i = it.indexOf("=");
                    if (i > 0) {
                        String n = it.substring(0, i);
                        String v = it.substring(i + 1, it.length());
                        // POST encodes values during request
                        ((PostMethod) request).addParameter(n, URLDecoder.decode(v, "UTF-8"));
                    } else {
                        mLogger.warn(
                                /* (non-Javadoc)
                                 * @i18n.test
                                 * @org-mes="ignoring bad token (missing '=' char) in query string: " + p[0]
                                 */
                                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                        "051018-429", new Object[] { it }));
                    }
                }
            }
        } else {
            // This call takes an encoded (escaped) query string
            request.setQueryString(query);
        }

        // Put in the If-Modified-Since headers
        if (since != -1) {
            String lms = LZHttpUtils.getDateString(since);
            request.setRequestHeader(LZHttpUtils.IF_MODIFIED_SINCE, lms);
            mLogger.debug(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="proxying lms: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-450",
                            new Object[] { lms }));
        }

        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="setting up http client"
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-460"));
        HttpClient htc = null;
        if (mConnectionMgr != null) {
            htc = new HttpClient(mConnectionMgr);
        } else {
            htc = new HttpClient();
        }

        htc.setHostConfiguration(hcfg);

        // This is the data timeout
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="timeout set to " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-478",
                        new Object[] { timeout }));
        htc.getParams().setSoTimeout(timeout);

        // Set connection timeout the same
        htc.getHttpConnectionManager().getParams().setConnectionTimeout(mConnectionTimeout);

        // Set timeout for getting a connection
        htc.getParams().setConnectionManagerTimeout(mConnectionPoolTimeout);

        // TODO: [2003-03-05 bloch] this should be more configurable (per app?)
        if (!isPost) {
            request.setFollowRedirects(mFollowRedirects > 0);
        }

        long t1 = System.currentTimeMillis();
        mLogger.debug("starting remote request");
        int rc = htc.executeMethod(hcfg, request);
        String status = HttpStatus.getStatusText(rc);
        if (status == null) {
            status = "" + rc;
        }
        mLogger.debug(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="remote response status: " + p[0]
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-504",
                        new Object[] { status }));

        HttpData data = null;
        if (isRedirect(rc) && mFollowRedirects > redirCount) {
            String loc = request.getResponseHeader("Location").toString();
            String hostURI = loc.substring(loc.indexOf(": ") + 2, loc.length());
            mLogger.info(
                    /* (non-Javadoc)
                     * @i18n.test
                     * @org-mes="Following URL from redirect: " + p[0]
                     */
                    org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-517",
                            new Object[] { hostURI }));
            long t2 = System.currentTimeMillis();
            if (timeout > 0) {
                timeout -= (t2 - t1);
                if (timeout < 0) {
                    throw new InterruptedIOException(
                            /* (non-Javadoc)
                             * @i18n.test
                             * @org-mes=p[0] + " timed out after redirecting to " + p[1]
                             */
                            org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(),
                                    "051018-529", new Object[] { surl, loc }));
                }
            }

            data = getDataOnce(req, res, since, hostURI, redirCount++, timeout);
        } else {
            data = new HttpData(request, rc);
        }

        if (req != null && res != null) {
            // proxy response headers
            LZHttpUtils.proxyResponseHeaders(request, res, req.isSecure());
        }

        return data;

    } catch (ConnectTimeoutException ce) {
        // Transduce to an InterrupedIOException, since lps takes these to be timeouts.
        if (request != null) {
            request.releaseConnection();
        }
        throw new InterruptedIOException(
                /* (non-Javadoc)
                 * @i18n.test
                 * @org-mes="connecting to " + p[0] + ":" + p[1] + " timed out beyond " + p[2] + " msecs."
                 */
                org.openlaszlo.i18n.LaszloMessages.getMessage(HTTPDataSource.class.getName(), "051018-557",
                        new Object[] { hcfg.getHost(), hcfg.getPort(), mConnectionTimeout }));
    } catch (HttpRecoverableException hre) {
        if (request != null) {
            request.releaseConnection();
        }
        throw hre;
    } catch (HttpException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    } catch (IOException ie) {
        if (request != null) {
            request.releaseConnection();
        }
        throw ie;
    } catch (RuntimeException e) {
        if (request != null) {
            request.releaseConnection();
        }
        throw e;
    }
}

From source file:phex.download.MagnetData.java

public static MagnetData parseFromURI(URI uri) {
    String protocol = uri.getScheme();
    if (!"magnet".equals(protocol)) {
        return null;
    }/*w w  w.  j  a  va 2  s . c om*/

    MagnetData magnetData = new MagnetData();

    String urlQuery = uri.getEscapedQuery();

    StringTokenizer tokenizer = new StringTokenizer(urlQuery, "&");
    while (tokenizer.hasMoreTokens()) {
        String param = tokenizer.nextToken().trim();
        int seperatorIdx = param.indexOf('=');
        if (seperatorIdx == -1) {// no = found.
            continue;
        }
        String key = param.substring(0, seperatorIdx);
        String value = param.substring(seperatorIdx + 1);
        value = URLCodecUtils.decodeURL(value);

        switch (key) {
        case "xt":
            magnetData.addExactTopic(value);
            break;
        case "xs":
            magnetData.addExactSubstitute(value);
            break;
        case "as":
            magnetData.addAcceptableSubstitute(value);
            break;
        case "dn":
            magnetData.setDisplayName(value);
            break;
        case "kt":
            magnetData.setKeywordTopic(value);
            break;
        }
    }
    return magnetData;
}