/*
* Licensed Materials - Property of IBM Corp.
* IBM UrbanCode Build
* IBM UrbanCode Deploy
* IBM UrbanCode Release
* IBM AnthillPro
* (c) Copyright IBM Corporation 2002, 2016. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*/
package com.urbancode.air.plugin.webutilities

/**
 * Encodes a url
 *
 * @param   url     Accepts any URL as defined in RFC 2396 and RFC 2732.
 * @return          A String object with components encoded according to the escaping mechanism defined in RFC 2396
 */
static public String encodeURL(url) {
    URI aURI
    URL aURL

    // This validates the URL
    try {
        aURL = new java.net.URL(url)
        // See rfc7230 section 2.7.1
        if ((aURL.getProtocol().equalsIgnoreCase('http') || aURL.getProtocol().equalsIgnoreCase('https')) && !aURL.getHost()) {
            throw new MalformedURLException('No hostname was found. Hostname is required for the http or https protocals. See rfc7230 section 2.7.1.')
        }
        if (aURL.getUserInfo()) {
            throw new MalformedURLException('It must not include a userinfo option as part of its authority. See rfc7230 section 2.7.1.')
        }
    } catch (MalformedURLException e) {
        print ("The inputted URL ${url}, is incorrectly formed.")
        if (e.getLocalizedMessage()) {
            print (e.getLocalizedMessage())
        }
        else {
            print ('Either no legal protocol (Example: http, https, file, and jar) could be found in a specification string or the string could not be parsed.')
        }
        println ('Example of correctly formed URL: <protocol>://<authority><path>?<query>#<fragment> or <scheme>://<authority>')
        throw e
    }

    // URI construtor quotes, or encodes, URL to FRC 2396 for each segement.
    try {
        aURI = new java.net.URI(aURL.getProtocol(), aURL.getUserInfo(), aURL.getHost(), aURL.getPort(), aURL.getPath(), aURL.getQuery(), aURL.getRef())
    } catch (URISyntaxException e) {
        println ("Inputted URL, ${url}, violates RFC 2396. Reason: " + e.getReason())
        throw e
    }

    // This returns the validated and encoded URL into a string
    try {
        String result = aURI.toURL().toString()
        return result
    } catch (MalformedURLException e) {
        println ('The inputted URL is incorrectly formed: ' + e.getMessage())
        throw e
    }
}
