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

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

Introduction

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

Prototype

public char[] getRawPath() 

Source Link

Document

Get the raw-escaped path.

Usage

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

@SuppressWarnings("deprecation")
@Override/*  www .  ja v a 2s. 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);
                }
            }
        }
    }
}

From source file:org.apache.jackrabbit.spi2dav.RepositoryServiceImpl.java

private static String obtainAbsolutePathFromUri(String uri) {
    try {//w w w.j  a va2 s.  com
        java.net.URI u = new java.net.URI(uri);
        StringBuilder sb = new StringBuilder();
        sb.append(u.getRawPath());
        if (u.getRawQuery() != null) {
            sb.append("?").append(u.getRawQuery());
        }
        return sb.toString();
    } catch (java.net.URISyntaxException ex) {
        log.warn("parsing " + uri, ex);
        return uri;
    }
}

From source file:org.zaproxy.zap.extension.ascanrulesBeta.RemoteCodeExecutionCVE20121823.java

private static URI createAttackUri(URI originalURI, String attackParam) {
    StringBuilder strBuilder = new StringBuilder();
    strBuilder.append(originalURI.getScheme()).append("://").append(originalURI.getEscapedAuthority());
    strBuilder.append(originalURI.getRawPath() != null ? originalURI.getEscapedPath() : "/")
            .append(attackParam);/*  w  ww .jav a 2  s .  com*/
    String uri = strBuilder.toString();
    try {
        return new URI(uri, true);
    } catch (URIException e) {
        log.warn("Failed to create attack URI [" + uri + "], cause: " + e.getMessage());
    }
    return null;
}

From source file:org.zaproxy.zap.extension.spiderAjax.HttpPrefixUriValidator.java

/**
 * Constructs a {@code HttpPrefixFetchFilter} using the given {@code URI} as prefix.
 *
 * <p>The user info, query component and fragment of the given {@code URI} are discarded. The
 * scheme and domain comparisons are done in a case insensitive way while the path component
 * comparison is case sensitive./*w  w w .  j a  v a 2 s. co m*/
 *
 * @param prefix the {@code URI} that will be used as prefix
 * @throws IllegalArgumentException if any of the following conditions is {@code true}:
 *     <ul>
 *       <li>The given {@code prefix} is {@code null};
 *       <li>The given {@code prefix} has {@code null} scheme;
 *       <li>The scheme of the given {@code prefix} is not HTTP or HTTPS;
 *       <li>The given {@code prefix} has {@code null} host;
 *       <li>The given {@code prefix} has malformed host.
 *     </ul>
 */
public HttpPrefixUriValidator(URI prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("Parameter prefix must not be null.");
    }

    char[] rawScheme = prefix.getRawScheme();
    if (rawScheme == null) {
        throw new IllegalArgumentException("Parameter prefix must have a scheme.");
    }
    String normalisedScheme = normalisedScheme(rawScheme);
    if (!isHttpOrHttps(normalisedScheme)) {
        throw new IllegalArgumentException("The prefix's scheme must be HTTP or HTTPS.");
    }
    scheme = normalisedScheme;

    if (prefix.getRawHost() == null) {
        throw new IllegalArgumentException("Parameter prefix must have a host.");
    }
    try {
        host = normalisedHost(prefix);
    } catch (URIException e) {
        throw new IllegalArgumentException("Failed to obtain the host from the prefix:", e);
    }

    port = normalisedPort(scheme, prefix.getPort());
    path = prefix.getRawPath();
}

From source file:org.zaproxy.zap.extension.spiderAjax.HttpPrefixUriValidator.java

/**
 * Tells whether or not the given URI is valid, by starting or not with the defined prefix.
 *
 * @param uri the uri to be validated/*  w ww  .j a  va  2  s.co m*/
 * @return {@code true} if valid, that is, the {@code uri} starts with the {@code prefix},
 *     {@code false} otherwise
 */
public boolean isValid(URI uri) {
    if (uri == null) {
        return false;
    }

    String otherScheme = normalisedScheme(uri.getRawScheme());
    if (port != normalisedPort(otherScheme, uri.getPort())) {
        return false;
    }

    if (!scheme.equals(otherScheme)) {
        return false;
    }

    if (!hasSameHost(uri)) {
        return false;
    }

    if (!startsWith(uri.getRawPath(), path)) {
        return false;
    }

    return true;
}

From source file:org.zaproxy.zap.spider.filters.HttpPrefixFetchFilter.java

/**
 * Constructs a {@code HttpPrefixFetchFilter} using the given {@code URI} as prefix.
 * <p>//from w w w.ja v  a 2  s.  c  o  m
 * The user info, query component and fragment of the given {@code URI} are discarded. The scheme and domain comparisons are
 * done in a case insensitive way while the path component comparison is case sensitive.
 *
 * @param prefix the {@code URI} that will be used as prefix
 * @throws IllegalArgumentException if any of the following conditions is {@code true}:
 *             <ul>
 *             <li>The given {@code prefix} is {@code null};</li>
 *             <li>The given {@code prefix} has {@code null} scheme;</li>
 *             <li>The scheme of the given {@code prefix} is not HTTP or HTTPS;</li>
 *             <li>The given {@code prefix} has {@code null} host;</li>
 *             <li>The given {@code prefix} has malformed host.</li>
 *             </ul>
 */
public HttpPrefixFetchFilter(URI prefix) {
    if (prefix == null) {
        throw new IllegalArgumentException("Parameter prefix must not be null.");
    }

    char[] rawScheme = prefix.getRawScheme();
    if (rawScheme == null) {
        throw new IllegalArgumentException("Parameter prefix must have a scheme.");
    }
    String normalisedScheme = normalisedScheme(rawScheme);
    if (!isHttpOrHttps(normalisedScheme)) {
        throw new IllegalArgumentException("The prefix's scheme must be HTTP or HTTPS.");
    }
    scheme = normalisedScheme;

    if (prefix.getRawHost() == null) {
        throw new IllegalArgumentException("Parameter prefix must have a host.");
    }
    try {
        host = normalisedHost(prefix);
    } catch (URIException e) {
        throw new IllegalArgumentException("Failed to obtain the host from the prefix:", e);
    }

    port = normalisedPort(scheme, prefix.getPort());
    path = prefix.getRawPath();
}

From source file:org.zaproxy.zap.spider.filters.HttpPrefixFetchFilter.java

/**
 * Filters any URI that does not start with the defined prefix.
 * //  www  .  j ava  2  s  .  c om
 * @return {@code FetchStatus.VALID} if the {@code uri} starts with the {@code prefix}, {@code FetchStatus.OUT_OF_SCOPE}
 *         otherwise
 */
@Override
public FetchStatus checkFilter(URI uri) {
    if (uri == null) {
        return FetchStatus.OUT_OF_SCOPE;
    }

    String otherScheme = normalisedScheme(uri.getRawScheme());
    if (port != normalisedPort(otherScheme, uri.getPort())) {
        return FetchStatus.OUT_OF_SCOPE;
    }

    if (!scheme.equals(otherScheme)) {
        return FetchStatus.OUT_OF_SCOPE;
    }

    if (!hasSameHost(uri)) {
        return FetchStatus.OUT_OF_SCOPE;
    }

    if (!startsWith(uri.getRawPath(), path)) {
        return FetchStatus.OUT_OF_SCOPE;
    }

    return FetchStatus.VALID;
}