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

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

Introduction

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

Prototype

public String getQuery() throws URIException 

Source Link

Document

Get the query.

Usage

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

/**
 * Adds the cas ticket./*from   w  w  w.  j ava  2 s .  c  o m*/
 * 
 * @param method
 *            the method
 * @throws IOException
 *             Signals that an I/O exception has occurred.
 * @throws MotuCasException
 */
public static void addCASTicket(HttpMethod method) throws IOException, MotuCasException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicket(HttpMethod) - entering : debugHttpMethod BEFORE  "
                + HttpClientCAS.debugHttpMethod(method));
    }

    if (HttpClientCAS.addCASTicketFromTGT(method)) {
        return;
    }

    if (!AuthenticationHolder.isCASAuthentication()) {
        if (LOG.isDebugEnabled()) {
            LOG.debug("addCASTicket(HttpMethod) - exiting - NO CAS AUTHENTICATION : debugHttpMethod AFTER  "
                    + HttpClientCAS.debugHttpMethod(method));
        }
        return;
    }

    String newURIAsString = AssertionUtils.addCASTicket(method.getURI().getEscapedURI());
    if (!AssertionUtils.hasCASTicket(newURIAsString)) {
        newURIAsString = AssertionUtils.addCASTicket(method.getURI().getEscapedURI(),
                AuthenticationHolder.getUser());

        if (!AssertionUtils.hasCASTicket(newURIAsString)) {

            String login = AuthenticationHolder.getUserLogin();
            throw new MotuCasException(String.format(
                    "Unable to access resource '%s'. This resource has been declared as CASified, but the Motu application/API can't retrieve any ticket from CAS via REST. \nFor information, current user login is:'%s'",
                    method.getURI().getEscapedURI(), login));

        }
    }

    URI newURI = new URI(newURIAsString, true);

    // method.setURI(newURI);
    method.setPath(newURI.getPath());
    method.setQueryString(newURI.getQuery());
    // System.out.println(newURI.getPathQuery());
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicket(HttpMethod) - exiting : debugHttpMethod AFTER  "
                + HttpClientCAS.debugHttpMethod(method));
    }

}

From source file:fr.cls.atoll.motu.library.cas.HttpClientCAS.java

/**
 * Adds the cas ticket from tgt.//w ww.  j  a  v  a 2  s  .  c o  m
 *
 * @param method the method
 * @return true, if successful
 * @throws MotuCasException the motu cas exception
 * @throws URIException the uRI exception
 * @throws IOException Signals that an I/O exception has occurred.
 */
public static boolean addCASTicketFromTGT(HttpMethod method)
        throws MotuCasException, URIException, IOException {
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicketFromTGT(HttpMethod) - entering : debugHttpMethod BEFORE  "
                + HttpClientCAS.debugHttpMethod(method));
    }

    Header headerTgt = method.getRequestHeader(HttpClientCAS.TGT_PARAM);
    Header headerCasRestUrl = method.getRequestHeader(HttpClientCAS.CAS_REST_URL_PARAM);

    if ((headerTgt == null) || (headerCasRestUrl == null)) {
        return false;
    }
    String ticketGrantingTicket = headerTgt.getValue();
    String casRestUrl = headerCasRestUrl.getValue();

    if ((RestUtil.isNullOrEmpty(ticketGrantingTicket)) || (RestUtil.isNullOrEmpty(casRestUrl))) {
        return false;
    }

    String ticket = RestUtil.loginToCASWithTGT(casRestUrl, ticketGrantingTicket,
            method.getURI().getEscapedURI());

    String newURIAsString = AssertionUtils.addCASTicket(ticket, method.getURI().getEscapedURI());

    if (!AssertionUtils.hasCASTicket(newURIAsString)) {
        throw new MotuCasException(String.format(
                "Unable to access resource '%s'. This resource has been declared as CASified, but the Motu application/API can't retrieve any ticket from CAS via REST. \nFor information, current TGT is:'%s', CAS REST url is:'%s'",
                method.getURI().getEscapedURI(), ticketGrantingTicket, casRestUrl));

    }

    URI newURI = new URI(newURIAsString, true);

    // method.setURI(newURI);
    method.setPath(newURI.getPath());
    method.setQueryString(newURI.getQuery());
    // System.out.println(newURI.getPathQuery());
    if (LOG.isDebugEnabled()) {
        LOG.debug("addCASTicketFromTGT(HttpMethod) - exiting : debugHttpMethod AFTER  "
                + HttpClientCAS.debugHttpMethod(method));
    }

    return true;

}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute webdav request./*from   w w  w .  j a v  a 2  s.c o m*/
 *
 * @param httpClient http client instance
 * @param method     webdav method
 * @return Responses enumeration
 * @throws IOException on error
 */
public static MultiStatusResponse[] executeMethod(HttpClient httpClient, ExchangeDavMethod method)
        throws IOException {
    MultiStatusResponse[] responses = null;
    try {
        int status = httpClient.executeMethod(method);

        // need to follow redirects (once) on public folders
        if (isRedirect(status)) {
            method.releaseConnection();
            URI targetUri = new URI(method.getResponseHeader("Location").getValue(), true);
            checkExpiredSession(targetUri.getQuery());
            method.setURI(targetUri);
            status = httpClient.executeMethod(method);
        }

        if (status != HttpStatus.SC_MULTI_STATUS) {
            throw buildHttpException(method);
        }
        responses = method.getResponses();

    } finally {
        method.releaseConnection();
    }
    return responses;
}

From source file:davmail.http.DavGatewayHttpClientFacade.java

/**
 * Execute webdav request.// ww w .ja  v a2  s  . c  om
 *
 * @param httpClient http client instance
 * @param method     webdav method
 * @return Responses enumeration
 * @throws IOException on error
 */
public static MultiStatusResponse[] executeMethod(HttpClient httpClient, DavMethodBase method)
        throws IOException {
    MultiStatusResponse[] responses = null;
    try {
        int status = httpClient.executeMethod(method);

        // need to follow redirects (once) on public folders
        if (isRedirect(status)) {
            method.releaseConnection();
            URI targetUri = new URI(method.getResponseHeader("Location").getValue(), true);
            checkExpiredSession(targetUri.getQuery());
            method.setURI(targetUri);
            status = httpClient.executeMethod(method);
        }

        if (status != HttpStatus.SC_MULTI_STATUS) {
            throw buildHttpException(method);
        }
        responses = method.getResponseBodyAsMultiStatus().getResponses();

    } catch (DavException e) {
        throw new IOException(e.getMessage());
    } finally {
        method.releaseConnection();
    }
    return responses;
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.EndpointRequestFilter.java

@Override
public void filterAbstractHttpRequest(SubmitContext context, AbstractHttpRequest<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String strURL = request.getEndpoint();
    strURL = PropertyExpander.expandProperties(context, strURL);
    try {/* www  . j av a 2s. c om*/
        if (StringUtils.hasContent(strURL)) {
            URI uri = new URI(strURL, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            httpMethod.setURI(new java.net.URI(uri.getScheme(), uri.getUserinfo(), uri.getHost(), uri.getPort(),
                    (uri.getPath()) == null ? "/" : uri.getPath(), uri.getQuery(), uri.getFragment()));
        }
    } catch (Exception e) {
        SoapUI.logError(e);
    }
}

From source file:com.eviware.soapui.impl.wsdl.submit.transports.http.HttpClientRequestTransport.java

private ExtendedGetMethod followRedirects(HttpClient httpClient, int redirectCount,
        ExtendedHttpMethod httpMethod, org.apache.http.HttpResponse httpResponse, HttpContext httpContext)
        throws Exception {
    ExtendedGetMethod getMethod = new ExtendedGetMethod();

    getMethod.getMetrics().getTotalTimer().set(httpMethod.getMetrics().getTotalTimer().getStart(),
            httpMethod.getMetrics().getTotalTimer().getStop());
    getMethod.getMetrics().setHttpMethod(httpMethod.getMethod());
    captureMetrics(httpMethod, httpClient);

    String location = httpResponse.getFirstHeader("Location").getValue();
    URI uri = new URI(new URI(httpMethod.getURI().toString(), true), location, true);
    java.net.URI newUri = new java.net.URI(uri.getScheme(), uri.getUserinfo(), uri.getHost(), uri.getPort(),
            uri.getPath(), uri.getQuery(), uri.getFragment());
    getMethod.setURI(newUri);/*from w w  w .j a v a  2s  .  com*/

    org.apache.http.HttpResponse response = HttpClientSupport.execute(getMethod, httpContext);

    if (isRedirectResponse(response.getStatusLine().getStatusCode())) {
        if (redirectCount == 10)
            throw new Exception("Maximum number of Redirects reached [10]");

        try {
            getMethod = followRedirects(httpClient, redirectCount + 1, getMethod, response, httpContext);
        } finally {
            //getMethod.releaseConnection();
        }
    }

    for (Header header : httpMethod.getAllHeaders())
        getMethod.addHeader(header);

    return getMethod;
}

From source file:de.innovationgate.utils.URLBuilder.java

/**
 * Creates a URLBuilder that parses an existing URI
 * @param uri The URI to parse//from   w w w  .  j  a  va  2 s  .  co m
 */
public URLBuilder(URI uri) throws URIException {
    this(uri.getScheme(), uri.getPort(), uri.getHost(), uri.getPath(), uri.getQuery(), uri.getFragment(),
            "UTF-8");
}

From source file:com.jivesoftware.os.jive.utils.http.client.ApacheHttpClient31BackedHttpClient.java

private void signWithOAuth(HttpMethod method) throws IOException {
    try {/* w w w . ja  va2s .  co m*/
        HostConfiguration hostConfiguration = client.getHostConfiguration();

        URI uri = method.getURI();
        URI newUri = new URI((isSSLEnabled) ? "https" : "http", uri.getUserinfo(), hostConfiguration.getHost(),
                hostConfiguration.getPort(), uri.getPath(), uri.getQuery(), uri.getFragment());

        method.setURI(newUri);

        //URI checkUri = method.getURI();
        //String checkUriString = checkUri.toString();
        CommonsHttp3OAuthConsumer oAuthConsumer = new CommonsHttp3OAuthConsumer(consumerKey, consumerSecret);
        oAuthConsumer.setTokenWithSecret(consumerKey, consumerSecret);
        oAuthConsumer.sign(method);
    } catch (Exception e) {
        throw new IOException("Failed to OAuth sign HTTPRequest", e);
    }
}

From source file:de.innovationgate.utils.URLBuilder.java

/**
 * Creates a URLBuilder that parses an existing URI
 * @param uri The URI to parse//from w ww .j  a  va2 s.c  om
 * @param encoding The encoding of URL parameters. The URLBuilder will decode them.
 */
public URLBuilder(URI uri, String encoding) throws URIException {
    this(uri.getScheme(), uri.getPort(), uri.getHost(), uri.getPath(), uri.getQuery(), uri.getFragment(),
            encoding);
}

From source file:com.eviware.soapui.impl.wsdl.submit.filters.HttpRequestFilter.java

@SuppressWarnings("deprecation")
@Override/*from  w w w  .j a va  2 s  .  c  om*/
public void filterHttpRequest(SubmitContext context, HttpRequestInterface<?> request) {
    HttpRequestBase httpMethod = (HttpRequestBase) context.getProperty(BaseHttpRequestTransport.HTTP_METHOD);

    String path = PropertyExpander.expandProperties(context, request.getPath());
    StringBuffer query = new StringBuffer();
    String encoding = System.getProperty("soapui.request.encoding", StringUtils.unquote(request.getEncoding()));

    StringToStringMap responseProperties = (StringToStringMap) context
            .getProperty(BaseHttpRequestTransport.RESPONSE_PROPERTIES);

    MimeMultipart formMp = "multipart/form-data".equals(request.getMediaType())
            && httpMethod instanceof HttpEntityEnclosingRequestBase ? new MimeMultipart() : null;

    RestParamsPropertyHolder params = request.getParams();

    for (int c = 0; c < params.getPropertyCount(); c++) {
        RestParamProperty param = params.getPropertyAt(c);

        String value = PropertyExpander.expandProperties(context, param.getValue());
        responseProperties.put(param.getName(), value);

        List<String> valueParts = sendEmptyParameters(request)
                || (!StringUtils.hasContent(value) && param.getRequired())
                        ? RestUtils.splitMultipleParametersEmptyIncluded(value,
                                request.getMultiValueDelimiter())
                        : RestUtils.splitMultipleParameters(value, request.getMultiValueDelimiter());

        // skip HEADER and TEMPLATE parameter encoding (TEMPLATE is encoded by
        // the URI handling further down)
        if (value != null && param.getStyle() != ParameterStyle.HEADER
                && param.getStyle() != ParameterStyle.TEMPLATE && !param.isDisableUrlEncoding()) {
            try {
                if (StringUtils.hasContent(encoding)) {
                    value = URLEncoder.encode(value, encoding);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i), encoding));
                } else {
                    value = URLEncoder.encode(value);
                    for (int i = 0; i < valueParts.size(); i++)
                        valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
                }
            } catch (UnsupportedEncodingException e1) {
                SoapUI.logError(e1);
                value = URLEncoder.encode(value);
                for (int i = 0; i < valueParts.size(); i++)
                    valueParts.set(i, URLEncoder.encode(valueParts.get(i)));
            }
            // URLEncoder replaces space with "+", but we want "%20".
            value = value.replaceAll("\\+", "%20");
            for (int i = 0; i < valueParts.size(); i++)
                valueParts.set(i, valueParts.get(i).replaceAll("\\+", "%20"));
        }

        if (param.getStyle() == ParameterStyle.QUERY && !sendEmptyParameters(request)) {
            if (!StringUtils.hasContent(value) && !param.getRequired())
                continue;
        }

        switch (param.getStyle()) {
        case HEADER:
            for (String valuePart : valueParts)
                httpMethod.addHeader(param.getName(), valuePart);
            break;
        case QUERY:
            if (formMp == null || !request.isPostQueryString()) {
                for (String valuePart : valueParts) {
                    if (query.length() > 0)
                        query.append('&');

                    query.append(URLEncoder.encode(param.getName()));
                    query.append('=');
                    if (StringUtils.hasContent(valuePart))
                        query.append(valuePart);
                }
            } else {
                try {
                    addFormMultipart(request, formMp, param.getName(), responseProperties.get(param.getName()));
                } catch (MessagingException e) {
                    SoapUI.logError(e);
                }
            }

            break;
        case TEMPLATE:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
                path = path.replaceAll("\\{" + param.getName() + "\\}", value == null ? "" : value);
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
            break;
        case MATRIX:
            try {
                value = getEncodedValue(value, encoding, param.isDisableUrlEncoding(),
                        request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }

            if (param.getType().equals(XmlBoolean.type.getName())) {
                if (value.toUpperCase().equals("TRUE") || value.equals("1")) {
                    path += ";" + param.getName();
                }
            } else {
                path += ";" + param.getName();
                if (StringUtils.hasContent(value)) {
                    path += "=" + value;
                }
            }
        case PLAIN:
            break;
        }
    }

    if (request.getSettings().getBoolean(HttpSettings.FORWARD_SLASHES))
        path = PathUtils.fixForwardSlashesInPath(path);

    if (PathUtils.isHttpPath(path)) {
        try {
            // URI(String) automatically URLencodes the input, so we need to
            // decode it first...
            URI uri = new URI(path, request.getSettings().getBoolean(HttpSettings.ENCODED_URLS));
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI, uri);
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(new java.net.URI(oldUri.getScheme(), oldUri.getUserInfo(), oldUri.getHost(),
                    oldUri.getPort(), (uri.getPath()) == null ? "/" : uri.getPath(), oldUri.getQuery(),
                    oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    } else if (StringUtils.hasContent(path)) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            String pathToSet = StringUtils.hasContent(oldUri.getRawPath()) && !"/".equals(oldUri.getRawPath())
                    ? oldUri.getRawPath() + path
                    : path;
            java.net.URI newUri = URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    pathToSet, oldUri.getQuery(), oldUri.getFragment());
            httpMethod.setURI(newUri);
            context.setProperty(BaseHttpRequestTransport.REQUEST_URI,
                    new URI(newUri.toString(), request.getSettings().getBoolean(HttpSettings.ENCODED_URLS)));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (query.length() > 0 && !request.isPostQueryString()) {
        try {
            java.net.URI oldUri = httpMethod.getURI();
            httpMethod.setURI(URIUtils.createURI(oldUri.getScheme(), oldUri.getHost(), oldUri.getPort(),
                    oldUri.getRawPath(), query.toString(), oldUri.getFragment()));
        } catch (Exception e) {
            SoapUI.logError(e);
        }
    }

    if (request instanceof RestRequest) {
        String acceptEncoding = ((RestRequest) request).getAccept();
        if (StringUtils.hasContent(acceptEncoding)) {
            httpMethod.setHeader("Accept", acceptEncoding);
        }
    }

    if (formMp != null) {
        // create request message
        try {
            if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
                String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                        request.isEntitizeProperties());
                if (StringUtils.hasContent(requestContent)) {
                    initRootPart(request, requestContent, formMp);
                }
            }

            for (Attachment attachment : request.getAttachments()) {
                MimeBodyPart part = new PreencodedMimeBodyPart("binary");

                if (attachment instanceof FileAttachment<?>) {
                    String name = attachment.getName();
                    if (StringUtils.hasContent(attachment.getContentID())
                            && !name.equals(attachment.getContentID()))
                        name = attachment.getContentID();

                    part.setDisposition(
                            "form-data; name=\"" + name + "\"; filename=\"" + attachment.getName() + "\"");
                } else
                    part.setDisposition("form-data; name=\"" + attachment.getName() + "\"");

                part.setDataHandler(new DataHandler(new AttachmentDataSource(attachment)));

                formMp.addBodyPart(part);
            }

            MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
            message.setContent(formMp);
            message.saveChanges();
            RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                    message, request);
            ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
            httpMethod.setHeader("Content-Type", mimeMessageRequestEntity.getContentType().getValue());
            httpMethod.setHeader("MIME-Version", "1.0");
        } catch (Throwable e) {
            SoapUI.logError(e);
        }
    } else if (request.hasRequestBody() && httpMethod instanceof HttpEntityEnclosingRequest) {
        if (StringUtils.hasContent(request.getMediaType()))
            httpMethod.setHeader("Content-Type", getContentTypeHeader(request.getMediaType(), encoding));

        if (request.isPostQueryString()) {
            try {
                ((HttpEntityEnclosingRequest) httpMethod).setEntity(new StringEntity(query.toString()));
            } catch (UnsupportedEncodingException e) {
                SoapUI.logError(e);
            }
        } else {
            String requestContent = PropertyExpander.expandProperties(context, request.getRequestContent(),
                    request.isEntitizeProperties());
            List<Attachment> attachments = new ArrayList<Attachment>();

            for (Attachment attachment : request.getAttachments()) {
                if (attachment.getContentType().equals(request.getMediaType())) {
                    attachments.add(attachment);
                }
            }

            if (StringUtils.hasContent(requestContent) && attachments.isEmpty()) {
                try {
                    byte[] content = encoding == null ? requestContent.getBytes()
                            : requestContent.getBytes(encoding);
                    ((HttpEntityEnclosingRequest) httpMethod).setEntity(new ByteArrayEntity(content));
                } catch (UnsupportedEncodingException e) {
                    ((HttpEntityEnclosingRequest) httpMethod)
                            .setEntity(new ByteArrayEntity(requestContent.getBytes()));
                }
            } else if (attachments.size() > 0) {
                try {
                    MimeMultipart mp = null;

                    if (StringUtils.hasContent(requestContent)) {
                        mp = new MimeMultipart();
                        initRootPart(request, requestContent, mp);
                    } else if (attachments.size() == 1) {
                        ((HttpEntityEnclosingRequest) httpMethod)
                                .setEntity(new InputStreamEntity(attachments.get(0).getInputStream(), -1));

                        httpMethod.setHeader("Content-Type",
                                getContentTypeHeader(request.getMediaType(), encoding));
                    }

                    if (((HttpEntityEnclosingRequest) httpMethod).getEntity() == null) {
                        if (mp == null)
                            mp = new MimeMultipart();

                        // init mimeparts
                        AttachmentUtils.addMimeParts(request, attachments, mp, new StringToStringMap());

                        // create request message
                        MimeMessage message = new MimeMessage(AttachmentUtils.JAVAMAIL_SESSION);
                        message.setContent(mp);
                        message.saveChanges();
                        RestRequestMimeMessageRequestEntity mimeMessageRequestEntity = new RestRequestMimeMessageRequestEntity(
                                message, request);
                        ((HttpEntityEnclosingRequest) httpMethod).setEntity(mimeMessageRequestEntity);
                        httpMethod.setHeader("Content-Type", getContentTypeHeader(
                                mimeMessageRequestEntity.getContentType().getValue(), encoding));
                        httpMethod.setHeader("MIME-Version", "1.0");
                    }
                } catch (Exception e) {
                    SoapUI.logError(e);
                }
            }
        }
    }
}