/*
 * [TestURIEncoding.java]
 *
 * Summary: Encode a URI using RFC 2396.
 *
 * Copyright: (c) 2009-2017 Roedy Green, Canadian Mind Products, http://mindprod.com
 *
 * Licence: This software may be copied and used freely for any purpose but military.
 *          http://mindprod.com/contact/nonmil.html
 *
 * Requires: JDK 1.8+
 *
 * Created with: JetBrains IntelliJ IDEA IDE http://www.jetbrains.com/idea/
 *
 * Version History:
 *  1.1 2009-01-28
 */
package com.mindprod.example;

import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;

import static java.lang.System.*;

/**
 * Encode a URI using RFC 2396.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 1.2 2011-01-18 add notes about plus + vs %20
 * @since 2009
 */
public final class TestURIEncoding
    {
    /**
     * Test URL encode via URI to URL.
     *
     * @param args not used
     *
     * @throws java.net.MalformedURLException if test URL illegal.
     * @throws java.net.URISyntaxException    if URL mangled.
     */
    public static void main( String[] args ) throws URISyntaxException, MalformedURLException
        {
        // reserved chars that have special meaning in URLs:
        // ; / ? : @ & = + $ ,
        // these characters are not reserved and don't need escaping.
        // - _ . ! ~ * ' ( )
        URI uri = new URI( "http",
                null /* @userinfo */,
                "www.example.com",
                -1 /* port */,
                "/you n I 10%/weird & weirder ne\u00e9", "q=abc&m=x and y &z=ne\u00e9",
                null /* fragment */ );
        out.println( uri.toString() );
        // prints http://www.example.com/you%20&%20I%2010%25?%20weird%20&%20weirder%20neé
        // ?q=abc&m=x%20and%20y%20&z=neé
        // note how fails to encode é
        out.println( uri.toASCIIString() );
        // prints http://www.example.com/you%20&%20I%2010%25?%20weird%20&%20weirder%20ne%C3%A9?q=abc&m=x%20and%20y%20
        // &z=ne%C3%A9
        // note how encodes é
        out.println( uri.toURL().toString() );
        // prints http://www.example.com/you%20&%20I%2010%25?%20weird%20&%20weirder%20neé
        // ?q=abc&m=x%20and%20y%20&z=neé
        // note how fails to encode é
        // Be aware Microsoft sometimes translates space to + instead of %20.  %20 is safer since all software will
        // decode it correctly but only some will decode +.
        // by that convention: you would get:
        // http://www.example.com/you+&+I+10%25?+weird+&+weirder+neé?q=abc&m=x+and+y+&z=neé
        }
    }