/*
* Licensed Materials - Property of IBM* and/or HCL**
* UrbanCode Deploy
* (c) Copyright IBM Corporation 2013, 2017. All Rights Reserved.
* (c) Copyright HCL Technologies Ltd. 2018. All Rights Reserved.
*
* U.S. Government Users Restricted Rights - Use, duplication or disclosure restricted by
* GSA ADP Schedule Contract with IBM Corp.
*
* * Trademark of International Business Machines
* ** Trademark of HCL Technologies Limited
*/
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
    }
}
