Java URL Create createURL(final String protocol, final String userInfo, final String host, final int port, final String path, final String query, final String ref)

Here you can find the source of createURL(final String protocol, final String userInfo, final String host, final int port, final String path, final String query, final String ref)

Description

create URL

License

GNU General Public License

Declaration

public static String createURL(final String protocol, final String userInfo, final String host, final int port,
            final String path, final String query, final String ref) throws MalformedURLException 

Method Source Code

//package com.java2s;
/**/*www . j  a v a2 s  . c o m*/
 *
 * ====================================================================================================================================================
 *         "AppWork Utilities" License
 *         The "AppWork Utilities" will be called [The Product] from now on.
 * ====================================================================================================================================================
 *         Copyright (c) 2009-2015, AppWork GmbH <e-mail@appwork.org>
 *         Schwabacher Stra?e 117
 *         90763 F?rth
 *         Germany
 * === Preamble ===
 *     This license establishes the terms under which the [The Product] Source Code & Binary files may be used, copied, modified, distributed, and/or redistributed.
 *     The intent is that the AppWork GmbH is able to provide  their utilities library for free to non-commercial projects whereas commercial usage is only permitted after obtaining a commercial license.
 *     These terms apply to all files that have the [The Product] License header (IN the file), a <filename>.license or <filename>.info (like mylib.jar.info) file that contains a reference to this license.
 *
 * === 3rd Party Licences ===
 *     Some parts of the [The Product] use or reference 3rd party libraries and classes. These parts may have different licensing conditions. Please check the *.license and *.info files of included libraries
 *     to ensure that they are compatible to your use-case. Further more, some *.java have their own license. In this case, they have their license terms in the java file header.
 *
 * === Definition: Commercial Usage ===
 *     If anybody or any organization is generating income (directly or indirectly) by using [The Product] or if there's any commercial interest or aspect in what you are doing, we consider this as a commercial usage.
 *     If your use-case is neither strictly private nor strictly educational, it is commercial. If you are unsure whether your use-case is commercial or not, consider it as commercial or contact as.
 * === Dual Licensing ===
 * === Commercial Usage ===
 *     If you want to use [The Product] in a commercial way (see definition above), you have to obtain a paid license from AppWork GmbH.
 *     Contact AppWork for further details: e-mail@appwork.org
 * === Non-Commercial Usage ===
 *     If there is no commercial usage (see definition above), you may use [The Product] under the terms of the
 *     "GNU Affero General Public License" (http://www.gnu.org/licenses/agpl-3.0.en.html).
 *
 *     If the AGPL does not fit your needs, please contact us. We'll find a solution.
 * ====================================================================================================================================================
 * ==================================================================================================================================================== */

import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;

public class Main {
    public static String createURL(final String protocol, final String userInfo, final String host, final int port,
            final String path, final String query, final String ref) throws MalformedURLException {
        final StringBuilder sb = new StringBuilder();
        sb.append(protocol);
        sb.append("://");
        if (userInfo != null) {
            sb.append(userInfo);
            sb.append("@");
        }
        sb.append(host);
        if (port != -1) {
            sb.append(":");
            sb.append(port);
        }
        if (path != null) {
            final String encodedURLPath;
            try {
                encodedURLPath = encodeURLPathSegment(path);
            } catch (UnsupportedEncodingException shouldNeverHappen) {
                throw new MalformedURLException(shouldNeverHappen.getMessage());
            }
            if (encodedURLPath.startsWith("/")) {
                sb.append(encodedURLPath);
            } else {
                sb.append("/");
                sb.append(encodedURLPath);
            }
        } else {
            sb.append("/");
        }
        if (query != null) {
            sb.append("?");
            /**
             * TODO: implement encodeURLQuerySegment
             */
            sb.append(query);
        }
        if (ref != null) {
            sb.append("#");
            sb.append(ref);
        }
        return sb.toString();
    }

    public static URL createURL(final String url) throws MalformedURLException {
        final URL tmp = new URL(url.trim().replaceAll(" ", "%20"));
        final String newURL = createURL(tmp.getProtocol(), tmp.getUserInfo(), tmp.getHost(), tmp.getPort(),
                tmp.getPath(), tmp.getQuery(), tmp.getRef());
        return new URL(newURL);
    }

    /**
     * this method takes care of correct encoding of path segment of an URL
     *
     * @param urlPath
     * @return
     * @throws UnsupportedEncodingException
     */
    private static String encodeURLPathSegment(final String urlPath) throws UnsupportedEncodingException {
        if (urlPath != null) {
            boolean encodeRequired = false;
            for (int index = 0; index < urlPath.length(); index++) {
                final char c = urlPath.charAt(index);
                if (c == '"' || c == ' ' || c == '[' || c == ']' || c == '{' || c == '}') {
                    encodeRequired = true;
                    break;
                } else if (c > 127) {
                    encodeRequired = true;
                    break;
                }
            }
            if (encodeRequired) {
                final StringBuilder encodedURLPath = new StringBuilder();
                for (int index = 0; index < urlPath.length(); index++) {
                    final char c = urlPath.charAt(index);
                    if (c == ' ') {
                        encodedURLPath.append("%20");
                    } else if (c == '"') {
                        encodedURLPath.append("%22");
                    } else if (c == '[') {
                        encodedURLPath.append("%5B");
                    } else if (c == ']') {
                        encodedURLPath.append("%5D");
                    } else if (c == '{') {
                        encodedURLPath.append("%7B");
                    } else if (c == '}') {
                        encodedURLPath.append("%7D");
                    } else if (c <= 127) {
                        encodedURLPath.append(c);
                    } else {
                        encodedURLPath.append(URLEncoder.encode(String.valueOf(c), "UTF-8"));
                    }
                }
                return encodedURLPath.toString();
            }
        }
        return urlPath;
    }
}

Related

  1. convertToURL(String host)
  2. convertToURL(String url)
  3. convertToUrl(String[] paths)
  4. convertToURLs(String[] hosts)
  5. createURL(final String address)
  6. createUrl(final String spec)
  7. createURL(final String url)
  8. createURL(String fileName)
  9. createUrl(String spec)