mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/URIUtils.java

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/mobile/android/thirdparty/ch/boye/httpclientandroidlib/client/utils/URIUtils.java	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,331 @@
     1.4 +/*
     1.5 + * ====================================================================
     1.6 + *
     1.7 + *  Licensed to the Apache Software Foundation (ASF) under one or more
     1.8 + *  contributor license agreements.  See the NOTICE file distributed with
     1.9 + *  this work for additional information regarding copyright ownership.
    1.10 + *  The ASF licenses this file to You under the Apache License, Version 2.0
    1.11 + *  (the "License"); you may not use this file except in compliance with
    1.12 + *  the License.  You may obtain a copy of the License at
    1.13 + *
    1.14 + *      http://www.apache.org/licenses/LICENSE-2.0
    1.15 + *
    1.16 + *  Unless required by applicable law or agreed to in writing, software
    1.17 + *  distributed under the License is distributed on an "AS IS" BASIS,
    1.18 + *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    1.19 + *  See the License for the specific language governing permissions and
    1.20 + *  limitations under the License.
    1.21 + * ====================================================================
    1.22 + *
    1.23 + * This software consists of voluntary contributions made by many
    1.24 + * individuals on behalf of the Apache Software Foundation.  For more
    1.25 + * information on the Apache Software Foundation, please see
    1.26 + * <http://www.apache.org/>.
    1.27 + *
    1.28 + */
    1.29 +
    1.30 +package ch.boye.httpclientandroidlib.client.utils;
    1.31 +
    1.32 +import java.net.URI;
    1.33 +import java.net.URISyntaxException;
    1.34 +import java.util.Stack;
    1.35 +
    1.36 +import ch.boye.httpclientandroidlib.annotation.Immutable;
    1.37 +
    1.38 +import ch.boye.httpclientandroidlib.HttpHost;
    1.39 +
    1.40 +/**
    1.41 + * A collection of utilities for {@link URI URIs}, to workaround
    1.42 + * bugs within the class or for ease-of-use features.
    1.43 + *
    1.44 + * @since 4.0
    1.45 + */
    1.46 +@Immutable
    1.47 +public class URIUtils {
    1.48 +
    1.49 +     /**
    1.50 +         * Constructs a {@link URI} using all the parameters. This should be
    1.51 +         * used instead of
    1.52 +         * {@link URI#URI(String, String, String, int, String, String, String)}
    1.53 +         * or any of the other URI multi-argument URI constructors.
    1.54 +         *
    1.55 +         * @param scheme
    1.56 +         *            Scheme name
    1.57 +         * @param host
    1.58 +         *            Host name
    1.59 +         * @param port
    1.60 +         *            Port number
    1.61 +         * @param path
    1.62 +         *            Path
    1.63 +         * @param query
    1.64 +         *            Query
    1.65 +         * @param fragment
    1.66 +         *            Fragment
    1.67 +         *
    1.68 +         * @throws URISyntaxException
    1.69 +         *             If both a scheme and a path are given but the path is
    1.70 +         *             relative, if the URI string constructed from the given
    1.71 +         *             components violates RFC&nbsp;2396, or if the authority
    1.72 +         *             component of the string is present but cannot be parsed
    1.73 +         *             as a server-based authority
    1.74 +         */
    1.75 +    public static URI createURI(
    1.76 +            final String scheme,
    1.77 +            final String host,
    1.78 +            int port,
    1.79 +            final String path,
    1.80 +            final String query,
    1.81 +            final String fragment) throws URISyntaxException {
    1.82 +
    1.83 +        StringBuilder buffer = new StringBuilder();
    1.84 +        if (host != null) {
    1.85 +            if (scheme != null) {
    1.86 +                buffer.append(scheme);
    1.87 +                buffer.append("://");
    1.88 +            }
    1.89 +            buffer.append(host);
    1.90 +            if (port > 0) {
    1.91 +                buffer.append(':');
    1.92 +                buffer.append(port);
    1.93 +            }
    1.94 +        }
    1.95 +        if (path == null || !path.startsWith("/")) {
    1.96 +            buffer.append('/');
    1.97 +        }
    1.98 +        if (path != null) {
    1.99 +            buffer.append(path);
   1.100 +        }
   1.101 +        if (query != null) {
   1.102 +            buffer.append('?');
   1.103 +            buffer.append(query);
   1.104 +        }
   1.105 +        if (fragment != null) {
   1.106 +            buffer.append('#');
   1.107 +            buffer.append(fragment);
   1.108 +        }
   1.109 +        return new URI(buffer.toString());
   1.110 +    }
   1.111 +
   1.112 +    /**
   1.113 +     * A convenience method for creating a new {@link URI} whose scheme, host
   1.114 +     * and port are taken from the target host, but whose path, query and
   1.115 +     * fragment are taken from the existing URI. The fragment is only used if
   1.116 +     * dropFragment is false.
   1.117 +     *
   1.118 +     * @param uri
   1.119 +     *            Contains the path, query and fragment to use.
   1.120 +     * @param target
   1.121 +     *            Contains the scheme, host and port to use.
   1.122 +     * @param dropFragment
   1.123 +     *            True if the fragment should not be copied.
   1.124 +     *
   1.125 +     * @throws URISyntaxException
   1.126 +     *             If the resulting URI is invalid.
   1.127 +     */
   1.128 +    public static URI rewriteURI(
   1.129 +            final URI uri,
   1.130 +            final HttpHost target,
   1.131 +            boolean dropFragment) throws URISyntaxException {
   1.132 +        if (uri == null) {
   1.133 +            throw new IllegalArgumentException("URI may nor be null");
   1.134 +        }
   1.135 +        if (target != null) {
   1.136 +            return URIUtils.createURI(
   1.137 +                    target.getSchemeName(),
   1.138 +                    target.getHostName(),
   1.139 +                    target.getPort(),
   1.140 +                    normalizePath(uri.getRawPath()),
   1.141 +                    uri.getRawQuery(),
   1.142 +                    dropFragment ? null : uri.getRawFragment());
   1.143 +        } else {
   1.144 +            return URIUtils.createURI(
   1.145 +                    null,
   1.146 +                    null,
   1.147 +                    -1,
   1.148 +                    normalizePath(uri.getRawPath()),
   1.149 +                    uri.getRawQuery(),
   1.150 +                    dropFragment ? null : uri.getRawFragment());
   1.151 +        }
   1.152 +    }
   1.153 +
   1.154 +    private static String normalizePath(String path) {
   1.155 +        if (path == null) {
   1.156 +            return null;
   1.157 +        }
   1.158 +        int n = 0;
   1.159 +        for (; n < path.length(); n++) {
   1.160 +            if (path.charAt(n) != '/') {
   1.161 +                break;
   1.162 +            }
   1.163 +        }
   1.164 +        if (n > 1) {
   1.165 +            path = path.substring(n - 1);
   1.166 +        }
   1.167 +        return path;
   1.168 +    }
   1.169 +
   1.170 +    /**
   1.171 +     * A convenience method for
   1.172 +     * {@link URIUtils#rewriteURI(URI, HttpHost, boolean)} that always keeps the
   1.173 +     * fragment.
   1.174 +     */
   1.175 +    public static URI rewriteURI(
   1.176 +            final URI uri,
   1.177 +            final HttpHost target) throws URISyntaxException {
   1.178 +        return rewriteURI(uri, target, false);
   1.179 +    }
   1.180 +
   1.181 +    /**
   1.182 +     * Resolves a URI reference against a base URI. Work-around for bug in
   1.183 +     * java.net.URI (<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
   1.184 +     *
   1.185 +     * @param baseURI the base URI
   1.186 +     * @param reference the URI reference
   1.187 +     * @return the resulting URI
   1.188 +     */
   1.189 +    public static URI resolve(final URI baseURI, final String reference) {
   1.190 +        return URIUtils.resolve(baseURI, URI.create(reference));
   1.191 +    }
   1.192 +
   1.193 +    /**
   1.194 +     * Resolves a URI reference against a base URI. Work-around for bugs in
   1.195 +     * java.net.URI (e.g. <http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4708535>)
   1.196 +     *
   1.197 +     * @param baseURI the base URI
   1.198 +     * @param reference the URI reference
   1.199 +     * @return the resulting URI
   1.200 +     */
   1.201 +    public static URI resolve(final URI baseURI, URI reference){
   1.202 +        if (baseURI == null) {
   1.203 +            throw new IllegalArgumentException("Base URI may nor be null");
   1.204 +        }
   1.205 +        if (reference == null) {
   1.206 +            throw new IllegalArgumentException("Reference URI may nor be null");
   1.207 +        }
   1.208 +        String s = reference.toString();
   1.209 +        if (s.startsWith("?")) {
   1.210 +            return resolveReferenceStartingWithQueryString(baseURI, reference);
   1.211 +        }
   1.212 +        boolean emptyReference = s.length() == 0;
   1.213 +        if (emptyReference) {
   1.214 +            reference = URI.create("#");
   1.215 +        }
   1.216 +        URI resolved = baseURI.resolve(reference);
   1.217 +        if (emptyReference) {
   1.218 +            String resolvedString = resolved.toString();
   1.219 +            resolved = URI.create(resolvedString.substring(0,
   1.220 +                resolvedString.indexOf('#')));
   1.221 +        }
   1.222 +        return removeDotSegments(resolved);
   1.223 +    }
   1.224 +
   1.225 +    /**
   1.226 +     * Resolves a reference starting with a query string.
   1.227 +     *
   1.228 +     * @param baseURI the base URI
   1.229 +     * @param reference the URI reference starting with a query string
   1.230 +     * @return the resulting URI
   1.231 +     */
   1.232 +    private static URI resolveReferenceStartingWithQueryString(
   1.233 +            final URI baseURI, final URI reference) {
   1.234 +        String baseUri = baseURI.toString();
   1.235 +        baseUri = baseUri.indexOf('?') > -1 ?
   1.236 +            baseUri.substring(0, baseUri.indexOf('?')) : baseUri;
   1.237 +        return URI.create(baseUri + reference.toString());
   1.238 +    }
   1.239 +
   1.240 +    /**
   1.241 +     * Removes dot segments according to RFC 3986, section 5.2.4
   1.242 +     *
   1.243 +     * @param uri the original URI
   1.244 +     * @return the URI without dot segments
   1.245 +     */
   1.246 +    private static URI removeDotSegments(URI uri) {
   1.247 +        String path = uri.getPath();
   1.248 +        if ((path == null) || (path.indexOf("/.") == -1)) {
   1.249 +            // No dot segments to remove
   1.250 +            return uri;
   1.251 +        }
   1.252 +        String[] inputSegments = path.split("/");
   1.253 +        Stack<String> outputSegments = new Stack<String>();
   1.254 +        for (int i = 0; i < inputSegments.length; i++) {
   1.255 +            if ((inputSegments[i].length() == 0)
   1.256 +                || (".".equals(inputSegments[i]))) {
   1.257 +                // Do nothing
   1.258 +            } else if ("..".equals(inputSegments[i])) {
   1.259 +                if (!outputSegments.isEmpty()) {
   1.260 +                    outputSegments.pop();
   1.261 +                }
   1.262 +            } else {
   1.263 +                outputSegments.push(inputSegments[i]);
   1.264 +            }
   1.265 +        }
   1.266 +        StringBuilder outputBuffer = new StringBuilder();
   1.267 +        for (String outputSegment : outputSegments) {
   1.268 +            outputBuffer.append('/').append(outputSegment);
   1.269 +        }
   1.270 +        try {
   1.271 +            return new URI(uri.getScheme(), uri.getAuthority(),
   1.272 +                outputBuffer.toString(), uri.getQuery(), uri.getFragment());
   1.273 +        } catch (URISyntaxException e) {
   1.274 +            throw new IllegalArgumentException(e);
   1.275 +        }
   1.276 +    }
   1.277 +
   1.278 +    /**
   1.279 +     * Extracts target host from the given {@link URI}.
   1.280 +     * 
   1.281 +     * @param uri 
   1.282 +     * @return the target host if the URI is absolute or <code>null</null> if the URI is 
   1.283 +     * relative or does not contain a valid host name.
   1.284 +     * 
   1.285 +     * @since 4.1
   1.286 +     */
   1.287 +    public static HttpHost extractHost(final URI uri) {
   1.288 +        if (uri == null) {
   1.289 +            return null;
   1.290 +        }
   1.291 +        HttpHost target = null;
   1.292 +        if (uri.isAbsolute()) {
   1.293 +            int port = uri.getPort(); // may be overridden later
   1.294 +            String host = uri.getHost();
   1.295 +            if (host == null) { // normal parse failed; let's do it ourselves
   1.296 +                // authority does not seem to care about the valid character-set for host names
   1.297 +                host = uri.getAuthority();
   1.298 +                if (host != null) {
   1.299 +                    // Strip off any leading user credentials
   1.300 +                    int at = host.indexOf('@');
   1.301 +                    if (at >= 0) {
   1.302 +                        if (host.length() > at+1 ) {
   1.303 +                            host = host.substring(at+1);
   1.304 +                        } else {
   1.305 +                            host = null; // @ on its own
   1.306 +                        }
   1.307 +                    }
   1.308 +                    // Extract the port suffix, if present
   1.309 +                    if (host != null) { 
   1.310 +                        int colon = host.indexOf(':');
   1.311 +                        if (colon >= 0) {
   1.312 +                            if (colon+1 < host.length()) {
   1.313 +                                port = Integer.parseInt(host.substring(colon+1));
   1.314 +                            }
   1.315 +                            host = host.substring(0,colon);
   1.316 +                        }                
   1.317 +                    }                    
   1.318 +                }
   1.319 +            }
   1.320 +            String scheme = uri.getScheme();
   1.321 +            if (host != null) {
   1.322 +                target = new HttpHost(host, port, scheme);
   1.323 +            }
   1.324 +        }
   1.325 +        return target;
   1.326 +    }
   1.327 +    
   1.328 +    /**
   1.329 +     * This class should not be instantiated.
   1.330 +     */
   1.331 +    private URIUtils() {
   1.332 +    }
   1.333 +
   1.334 +}

mercurial