/*
 * @(#)Post.java
 *
 * Summary: simulates a browser posting a form to CGI via POST.
 *
 * Copyright: (c) 1998-2009 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.5+
 *
 * Created with: IntelliJ IDEA IDE.
 *
 * Version History:
 *  2.0 2009-02-20 - major refactoring. separate setParms and setPostParms. new send method. Post can have both types of parm.
 */
package com.mindprod.http;

import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLEncoder;

/**
 * simulates a browser posting a form to CGI via POST.
 * <p/>
 * See com.mindprod.submitter for sample code to use this class.
 *
 * @author Roedy Green, Canadian Mind Products
 * @version 2.0 2009-02-20 - major refactoring. separate setParms and setPostParms. new send method. Post can have both types of parm.
 * @since 1998
 */
public final class Post extends Http
    {
    // ------------------------------ FIELDS ------------------------------

    /**
     * parameters we send in the body of the message for a post.  c.f. parms[] send on tail of command.
     */
    private String[] postParms;

    // -------------------------- PUBLIC INSTANCE  METHODS --------------------------
    /**
     * Constructor
     */
    public Post()
        {
        }

    /**
     * Send a form full of data to the CGI host using POST
     * Must have done a setParms(optional) and setPostParms beforehand.
     *
     * @param url      URL of the website, including host, path but not the parms.
     *                 only http: protocol is supported.
     * @param encoding encoding of the byte stream result, usually UTF-8 or or ISO-8859-1.
     *
     * @return CGI host's response with headers and embedded length fields stripped
     */
    @SuppressWarnings( { "UnusedAssignment", "MethodNamesDifferingOnlyByCase", "WeakerAccess" } )
    public String send( URL url, String encoding )
        {
        try
            {
            // defaults
            responseCode = DEFAULT_RESPONSE_CODE;
            responseMessage = DEFAULT_RESPONSE_MESSAGE;

            final HttpURLConnection urlc = ( HttpURLConnection ) url.openConnection();
            urlc.setAllowUserInteraction( false );
            urlc.setDoInput( true );
            urlc.setDoOutput( true );// parms at the tail of this
            urlc.setUseCaches( false );
            urlc.setRequestMethod( "POST" );
            setStandardProperties( urlc );
            final byte[] encodedPostParms = getEncodedPostParms( encoding ).getBytes( "UTF-8" );
            // could set Referrer: here
            urlc.setRequestProperty( "Content-Length",
                    Integer.toString( encodedPostParms.length )
                    /* in bytes */ );
            urlc.setRequestProperty( "Content-Type",
                    "application/x-www-form-urlencoded" );

            urlc.connect();

            final OutputStream os = urlc.getOutputStream();
            // parms are the data content.
            os.write( encodedPostParms );
            os.close();

            return processResponse( encoding, urlc );
            }
        catch ( ClassCastException e )
            {
            // was not an http: url
            return null;
            }
        catch ( IOException e )
            {
            return null;
            }
        }

    /**
     * Send a form full of data to the CGI host using POST
     * setPostParms must have been called previously, and possibly setParms as well.
     *
     * @param host     domain of the website. no lead http:
     * @param port     -1 if default, 8081 for local echoserver.
     * @param action   action of form, page on website. Usually has a lead /.
     * @param encoding encoding of the byte stream result, usually UTF-8 or or ISO-8859-1.
     *
     * @return CGI host's response with headers and embedded length fields stripped
     */
    @SuppressWarnings( { "UnusedAssignment", "MethodNamesDifferingOnlyByCase" } )
    public String send( String host, int port, String action, String encoding )
        {
        try
            {
            // defaults
            responseCode = DEFAULT_RESPONSE_CODE;
            responseMessage = DEFAULT_RESPONSE_MESSAGE;

            // URL will encode target and parms.
            URL url = new URI( "http",
                    null,
                    host,
                    port,
                    action,
                    null,
                    null ).toURL();

            // these are the GET parms not the POST parms.  Normally they are empty.
            final String encodedParms = getEncodedParms( encoding );
            if ( encodedParms.length() > 0 )
                {
                url = new URL( url.toString() + getEncodedParms( encoding ) );
                }
            return send( url, encoding );
            }
        catch ( URISyntaxException e )
            {
            return null;
            }
        catch ( IOException e )
            {
            return null;
            }
        }// end post

    /**
     * set the parms that will be send with the initial command, in the Post body.
     *
     * @param postParms 0..n strings to be send as parameter, alternating keyword/value
     */
    public void setPostParms( final String... postParms )
        {
        assert ( postParms.length & 1 ) == 0 : "must have an even number of post parms, keyword=value";
        this.postParms = postParms;
        }

    // -------------------------- OTHER METHODS --------------------------

    /**
     * get the parms for the command encoded, separated with   & =.  no lead ?
     *
     * @param encoding encoding for URLEncoder
     *
     * @return all the parms in one string encoded without lead ?
     * @throws java.io.UnsupportedEncodingException
     *          if bad encoding
     */
    String getEncodedPostParms( String encoding ) throws UnsupportedEncodingException
        {
        if ( postParms == null || postParms.length == 0 )
            {
            return "";
            }
        int estLength = 10; // allow a few slots for multibyte chars
        for ( String p : postParms )
            {
            estLength += p.length() + 1;
            }
        final StringBuilder sb = new StringBuilder( estLength );
        for ( int i = 0; i < postParms.length - 1; i += 2 )
            {
            if ( i != 0 )
                {
                sb.append( "&" );
                }
            sb.append( URLEncoder.encode( postParms[ i ], encoding
                    /* encoding */ ) );
            sb.append( '=' );
            sb.append( URLEncoder.encode( postParms[ i + 1 ], encoding
                    /* encoding */ ) );
            }
        return sb.toString();
        }
    }