//$Id

package com.util;

//import Java
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.ArrayList;
import java.io.FileWriter;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.StringReader;
import java.io.InterruptedIOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.HttpURLConnection;
import java.net.Authenticator;
import java.net.PasswordAuthentication;
import java.net.URI;
import java.net.UnknownHostException;

/**
 * This class is used in communicating with the Zoho service.
 * Sends the request to Zoho service and receives the respone in string format. 
 * Uses the third party jar,HTTPClient.jar, for communicating with Zoho service.
 * 
 * @version 1.0
 */
public class URLDataHandler
{
    private static String hostAddress = null;
    public static boolean rememberCookie = false;
    
    //Catalina home
    private static String catalinaHome = System.getProperty("catalina.home");
    
    //File separator
    private static String fileSep = File.separator;

    //Location of proxySettings.conf
/*    private static String configFile = catalinaHome+fileSep+"webapps"+fileSep
        +"zoho"+fileSep+"WEB-INF"+fileSep+"classes"+fileSep+"resources"
        +fileSep+"proxySettings.conf"; */

    private static String configFile = "userSettings.conf";
    
    //Stores the proxy configurations
    private static Properties proxyProps = getProxyConfigurations();
    //
    static
    {
        try
        {
           // initSSLFactory();
           // CookieModule.setCookiePolicyHandler(null);
            hostAddress = java.net.InetAddress.getLocalHost().getHostAddress();
        }catch(Exception e)
        {
        }
        //sosticket = getTicket();
    }

    //

    
    /**
     * Executes the given URL(urlStr) and gives back the respone.
     * This method internally calls the {@link #getResponseFromURL}. 
     *
     * @param service - service name.
     * @param userName - user name.
     * @param ticket - Ticket.
     * @param xmlStr - XML string.
     * @param urlStr - URL to be executed
     * @param type - method type(GET/POST)
     * @return String - executes the URL and returns the response.
     */
    public static String getDataFromURL(String service,String userName,String ticket, String xmlStr,String urlStr,String type) throws Exception
    {
        Properties rsp = null;
        String respStr = "";
        //try
        {
            rsp = getResponseFromURL(service,userName,ticket, xmlStr,urlStr,type);
            respStr = rsp.getProperty("response");
            if(rsp == null )
            {
                rsp = getResponseFromURL(service,userName,ticket, xmlStr,urlStr,type);
            }else 
            {
                /*if(!checkCode(respStr) )
                  {
                  }*/
            }
        }/*catch(Exception e)
        {
            throw e;
        }*/        
        return respStr;
    }
    
    /**
     * Executes the given URL(urlStr) and gives back the respone.
     *
     * @param service - service name.
     * @param userName - user name.
     * @param ticket - Ticket.
     * @param xmlStr - XML string.
     * @param urlStr - URL to be executed
     * @param type - method type(GET/POST)
     * @return String - executes the URL and returns the response.
     */
    public static Properties getResponseFromURL(String service,String userName,String ticket, String xmlStr,String urlStr,String type) throws Exception
    {
        long tt=System.currentTimeMillis();   
         System.out.println("URL "+urlStr);
        int dataIndx=urlStr.indexOf("?");
        String urlst="";
        String data="";
        if(dataIndx!=-1)
        {    
          urlst=urlStr.substring(0,dataIndx);
          data=urlStr.substring(dataIndx+1);
        }
        System.out.println("data:"+data);  
        Properties prop = new Properties();
        URL url = new URL(urlStr);
        HttpURLConnection con=null;
        String resp ="NODATA";
        if(type.equals("POST"))
        {    
         con=getConnection(urlst,type);
        OutputStreamWriter out = new OutputStreamWriter(con.getOutputStream());
        out.write(data);
        out.flush();
        out.close();
        }else
        {
           con=getConnection(urlStr,type);
        
        }    
        InputStream is = con.getInputStream();
        BufferedReader rd = new BufferedReader(new InputStreamReader(is));
        StringBuffer sb = new StringBuffer();
        try
        {
            String line;
            while ((line = rd.readLine()) != null)
            {
                sb.append(line);
            }
        }
        finally
        {
            rd.close();
        }
        int rcode=con.getResponseCode();
        prop.setProperty("response",sb.toString());
        prop.setProperty("statusCode",rcode+"");
        System.out.println("my response :"+prop);   
        tt=System.currentTimeMillis()-tt;
        System.out.println("timetaken for response rajarajan:"+tt); 
        return prop;
    }

    /**
     * Reads the userSettings.conf file and returns the configured
     * details in Properties object.
     * userSettings.conf file is read from the location: 
     *   <tomcat_home>/webapps/ea/WEB-INF/classes/resources
     */
    private static Properties getProxyConfigurations()
    {
        Class c=null;
        Properties prop = null;
        try
        {
            c = Class.forName("com.util.URLDataHandler");
            InputStream s = c.getClassLoader().getResourceAsStream(configFile);
            prop = new Properties();
            prop.load(s);
        }
        catch(Exception e)
        {
            System.out.println("URLDataHandler:getProxyConfigurations:"+
                    "Exception while parsing the userSettings.conf");    
            e.printStackTrace();    
        }
        System.out.println("URLDataHandler:getProxyConfigurations:"+
                "ConfiguredProxyDetails::"+prop);    
        return prop;
    }
    private static HttpURLConnection  getConnection(String urlStr,String type) throws Exception
            {
          System.out.println("my getconnection called");  
          URL url = new URL(urlStr);
          HttpURLConnection con = (HttpURLConnection)url.openConnection();
          if(type.equals("POST") || type.equals("GET"))
          {
           con.setRequestMethod(type);
           con.setDoInput( true);
           con.setDoOutput(true);
          }

        //Configured proxy details
        int timeOut = 5000;
        //If the proxyProps was not intialized,intializes the same
        //here
        if(proxyProps == null)
        {
            proxyProps = getProxyConfigurations();
        }

        if(proxyProps != null)
        {
            boolean isProxyEnabled = false;
            String timeOutCnf = proxyProps.getProperty("requestTimeout");
            if(timeOutCnf != null && !timeOutCnf.trim().equals(""))
            {
                try
                {
                    timeOut = Integer.parseInt(timeOutCnf);
                }
                catch(Exception e)
                {
                    System.out.println("URLDataHandler::Exception in"+
                            " parsing configured timeout value:"+timeOutCnf);    
                }
            }

            String isPrxyEnbld = proxyProps.getProperty("isProxyEnabled");
            if(isPrxyEnbld != null && isPrxyEnbld.equals("true"))
            {
                isProxyEnabled = true;
            }
            if(isProxyEnabled)
            {
                String host = proxyProps.getProperty("host");
                String port = "80";
                try
                {
                    port = proxyProps.getProperty("port");
                }
                catch(Exception e)
                {
                    System.out.println("URLDataHandler::Exception in "+
                            "parsing the configured port value::"+
                            proxyProps.getProperty("port")+".So current"+
                            " port value is::"+port);    
                }
                String realm = proxyProps.getProperty("realm");
                final String user_Name = proxyProps.getProperty("username");
                final String password = proxyProps.getProperty("password");
                if(host != null && !host.trim().equals("") 
                        && user_Name != "" && !user_Name.trim().equals("") 
                        && password != "" && !password.trim().equals("")
                        && realm != null && !realm.trim().equals(""))
                {
                   // con.setCurrentProxy(host,port);
                    System.setProperty("proxySet", "true");
                    System.setProperty("http.proxyHost", host);
                    System.setProperty("http.proxyPort", port);
                    System.setProperty("https.proxyHost", host);
                    System.setProperty("httpSystem.out.println.proxyPort", port);
                    Authenticator.setDefault( new Authenticator()
                            {
                                protected PasswordAuthentication getPasswordAuthentication()
                    {
                        PasswordAuthentication pass = new PasswordAuthentication(user_Name, password.toCharArray());
                        return pass;
                    }
                    });
                }
                else
                {
                    System.out.println("URLDataHandler::Configured Proxy details"+
                            " are not proper in the userSettings.conf. "+
                            "So no proxy is set.");    
                }
            }
        }
        //System.out.println("URLDataHandler::Timeout set::"+timeOut);    
       // con.setTimeout(timeOut);
       return con;  

    
    }    
public static Properties getUserSettings()
{
  return proxyProps;
}    
public static String getUserProperty(String name)
{
   if(proxyProps!=null)
   {
       return proxyProps.getProperty(name); 
   }   
   return null;
}    
public static void main(String args[]) throws Exception
{
 String url="http://writer.zoho.com/GetDocs.do?fromIndex=0&perPage=12";
 long tt=System.currentTimeMillis();   
 Properties resp=getResponseFromURL("","","", "null",url,args[0]) ;
 tt=System.currentTimeMillis()-tt;
 System.out.println("timetaken for url connection:"+tt); 
 System.out.println("response:"+resp); 
}   
}
