// copyright (c) 1998-2005 Roedy Green, Canadian Mind Products
// based on work by Jonathan Revusky

// To encode strings use java.net.URLEncoder.encode;
// and Java.net.URLDecoder.decode or Request.
/*
 * copyright (c) 1998-2005
 * Roedy Green
 * Canadian Mind Products
 * #327 - 964 Heywood Avenue
 * Victoria, BC Canada V8V 2Y5
 * tel: (250) 361-9093
 * roedy g at mindprod dotcom
 * http://mindprod.com
 * 1.1 2007-07-19 improved handling of responseCode
 * 1.2 2007-07-27 use UTF-8 instead of 8859_1.
 * 1.3 2007-08-24 readStringBlocking, readBytesBlocking, encoding on Get
 * 1.4 2007-09-26 add TIMEOUT
 * 1.5 2007-12-30 add alternate get and post methods that take a full URL.
 * 1.6 2008-01-14 add gzip option on read
 */
package com.mindprod.http;

import java.io.IOException;
import java.io.InputStream;
import java.net.*;

/**
 * simulates a browser posting a form to CGI via GET. See com.mindprod.submitter for sample code to use this class.
 *
 * @author Roedy Green, Canadian Mind Products may be copied and used freely for any purpose but military.
 * @version 1.6 2008-01-14 add gzip option on read
 */
public final class Get
    {
// ------------------------------ FIELDS ------------------------------

    /**
     * Allow 50 seconds to connect
     */
    private static final int CONNECT_TIMEOUT = 50 * 1000;

    /**
     * Allow 40 seconds for a read to go without progress
     */
    private static final int READ_TIMEOUT = 40 * 1000;

    /**
     * responseCode from most recent post
     */
    private static int responseCode;
// -------------------------- PUBLIC STATIC METHODS --------------------------

    /**
     * Send a formful of data to the CGI host using GET.
     *
     * @param url      complete URL including get parms
     * @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 static String get( URL url, String encoding )
        {
        try
            {
            // O P E N

            final HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
            urlc.setAllowUserInteraction( false );
            urlc.setDoInput( true );
            urlc.setDoOutput( false );// nothing beyond original request
            urlc.setUseCaches( false );
            urlc.setRequestMethod( "GET" );
            urlc.setConnectTimeout( CONNECT_TIMEOUT );
            urlc.setReadTimeout( READ_TIMEOUT );
            urlc.setRequestProperty( "Accept",
                                     "text/html, image/png, image/jpeg, image/gif, application/x-java-serialized-object, text/x-java-source, text/xml, application/xml, "
                                     +
                                     "text/css, application/x-java-jnlp-file, text/plain, application/zip, application/octet-stream, *; q=.2, */*; q=.2" );

            urlc.connect();
            /* save responseCode for later retrieval */
            responseCode = urlc.getResponseCode();
            // get size of message. -1 means comes in an indeterminate number of chunks.
            int estimatedLength = urlc.getContentLength();
            if ( estimatedLength < 0 )
                {
                // quite common for no length field
                estimatedLength = 32 * 1024;
                }
            final InputStream is = urlc.getInputStream();

            // content encoding might be null
            final boolean gzipped = "gzip".equals( urlc.getContentEncoding() );

            // R E A D
            String result =
                    Read.readStringBlocking( is,
                                             estimatedLength,
                                             READ_TIMEOUT,
                                             gzipped,
                                             encoding );

            // C L O S E
            is.close();
            urlc.disconnect();

            return result;
            }

        catch ( IOException e )
            {
            return null;
            }
        }// end get

    /**
     * Send a formful of data to the CGI host using GET.
     *
     * @param host     host name of the website, Should be form:"www.mindprod.com", no lead http://.
     * @param port     -1 if default, 8081 for local echoserver.
     * @param encoding encoding of the byte stream result, usually UTF-8 or or ISO-8859-1.
     * @param action   action of form, page on website. Usually has a lead /.
     * @param parms    alternating parm value without = or ? not urlEncoded.
     *
     * @return CGI host's response with headers and embedded length fields stripped.
     */
    @SuppressWarnings({ "UnusedAssignment", "MethodNamesDifferingOnlyByCase" })
    public static String get( String host,
                              int port,
                              String encoding,
                              String action,
                              String... parms )
        {
        try
            {
            // O P E N
            final StringBuilder sb = new StringBuilder( 200 );
            for ( int i = 0; i < parms.length - 1; i += 2 )
                {
                if ( i != 0 )
                    {
                    sb.append( "&" );
                    }
                sb.append( URLEncoder.encode( parms[ i ], "UTF-8"
                                              /* encoding */ ) );
                sb.append( '=' );
                sb.append( URLEncoder.encode( parms[ i + 1 ], "UTF-8"
                                              /* encoding */ ) );
                }

            final String encodedParms = sb.toString();
            // O P E N

            // URL will encode target and parms.
            URL url = new URI( "http",
                               null,
                               host,
                               port,
                               action,
                               null
                               /* no query here, or would be double encoded */,
                               null ).toURL();
            url = new URL( url.toString() + '?' + encodedParms );

            return get( url, encoding );
            }
        catch ( URISyntaxException e )
            {
            return null;
            }
        catch ( IOException e )
            {
            return null;
            }
        }// end get

    /**
     * responseCode from most recent post
     *
     * @return responseCode
     */
    public static int getResponseCode()
        {
        return responseCode;
        }

// --------------------------- CONSTRUCTORS ---------------------------

    /**
     * Static only.  Prevent instantiation.
     */
    private Get()
        {
        }
    }