/*
 * 
 * Server
 */

import java.awt.geom.Point2D;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import jsky.coords.WorldCoords;
import jsky.coords.wcscon;

import net.mar.AnException;
import net.mar.FormatRS;
import net.mar.ParseCoords;
import net.mar.SLALIB;

import org.apache.log4j.Logger;

import uk.ac.roe.wfau.ATLASHTTPSession;
import uk.ac.roe.wfau.DatabaseConnection;
import uk.ac.roe.wfau.DatabaseURL;
import uk.ac.roe.wfau.FormatLines;
import uk.ac.roe.wfau.GESHTMLSchema;
import uk.ac.roe.wfau.HTMLSnippets;
import uk.ac.roe.wfau.ImageSelect;
import uk.ac.roe.wfau.JDBCDataTypes;
import uk.ac.roe.wfau.SQLMethods;
import uk.ac.roe.wfau.SesameClient;
import uk.ac.roe.wfau.TangentRectangle;
import uk.ac.roe.wfau.VDFSSchema;
import uk.ac.roe.wfau.VDFSSession;
import uk.ac.roe.wfau.VSASchema;
import uk.ac.roe.wfau.OSASchema;
import uk.ac.roe.wfau.WSAHTMLSchema;
import uk.ac.roe.wfau.WSASchema;
import uk.ac.roe.wfau.WSASession;

import com.javaexchange.dbConnectionBroker.DbConnectionBroker;

public class GetObject extends HttpServlet {
   /**
    * Log4j logger for record keeping 
    */
    private static Logger logger;
    
    //private DBConnectionManager connMgr; // previous connection pool
    private DbConnectionBroker myBroker;
    private static final int RUNNUM_UPPERLIMIT = 99999;

    private static int RunNumber = 0; // 'Unique' counter

    private static String tempPath;
    private static String colourTempPath;
    private static String photomTempPath;
    private static String LISTCGIDIRURL;
    private static String colourTempURL;
    private static int TARGETIDMODE=1;
    private static int POSITIONMODE=2;
    private static int CNAMEMODE=3;
    private static String progPath;
    private static int NOFILTERS=10; // list driven
    private static String tempURL;

    private static String filePrefix;

    private static String BASESQL = "SELECT  multiframedetector.filterid,MultiFrameDetector.extNum,MultiFrame.filename, "
            + "programmeid,CurrentAstrometry.*, "
            + "MultiframeDetector.axis1Length,MultiframeDetector.axis2Length "
            + "FROM    Multiframe "
            + "INNER JOIN MultiframeDetector ON Multiframe.multiframeID = MultiframeDetector.multiframeID "
            + "INNER JOIN CurrentAstrometry ON Multiframe.multiframeID = CurrentAstrometry.multiframeID AND "
            + "MultiframeDetector.extNum = CurrentAstrometry.extNum "
            + "INNER JOIN ProgrammeFrame ON Multiframe.multiframeID = programmeframe.multiframeID";

    private static String BASESQL_SELECT;
    private static String BASESQL_FROM;
    private static String BASESQL_WHERE;
    private static String COLOURCGIDIRURL;
    private static String WSACGIDIRURL;
 //   private String ukidss_database;
    private String defaultUKIDSSDatabase;
    private String defaultWorldDatabase;
    private String server;
    
    private static String [] VSASERVERS=null;
    private static String [] WSASERVERS=null;
    private static String [] VSACUSERVERS=null;
    private static String [] WSACUSERVERS=null;
    private static String [] WSANSSERVERS=null;
    
    private static final float MINCOLOURPIXSIZE=0.1f;
    private static final float MAXCOLOURSIZE=60.0f;
    private static final int MAXPIXSIZE=9000;
   
    
    private static synchronized int getNextRunNumber() {
        RunNumber++;

        if (RunNumber > RUNNUM_UPPERLIMIT) {
            RunNumber = 1;
        }
        ;

        return RunNumber;
    };

    public void init(ServletConfig conf) throws ServletException {
        super.init(conf);
        logger = Logger.getLogger("wsa.simple");
        logger.debug("initializing GetObject servlet");

        // read in global properties
        Properties properties = new Properties();
        String path = getServletContext().getRealPath("/");
        try {
            properties.load(new FileInputStream(path
                    + "WEB-INF/WSA.properties"));

        } catch (IOException e) {
            logger.error("GetObject, properties file not found");
            return;
        }
        server = properties.getProperty("server");
        WSASERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("WSASERVERS").trim());
        VSASERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("VSASERVERS").trim());
        WSACUSERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("WSACUSERVERS").trim());
        VSACUSERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("VSACUSERVERS").trim());
        WSANSSERVERS=FormatLines.commaSeparatedStringToStringArray(properties.getProperty("WSANSSERVERS").trim());
        
 //       String user = properties.getProperty("user");
 //      String passwd = properties.getProperty("passwd");
 //       ukidss_database = properties.getProperty("ukidss_database");
        defaultUKIDSSDatabase = properties.getProperty("defaultUKIDSSDatabase");
        defaultWorldDatabase = properties.getProperty("defaultWorldDatabase");
//        String public_database = properties.getProperty("public_database");
//       String poolLogfile = properties.getProperty("pool.logfile");
        colourTempPath = properties.getProperty("colourTempPath");
        colourTempURL = properties.getProperty("colourTempURL");
        tempPath=properties.getProperty("GetImageTempPath");
        photomTempPath=properties.getProperty("photomTempPath");
        LISTCGIDIRURL=properties.getProperty("LISTCGIDIRURL");
        progPath = properties.getProperty("GetImageProgPath");
        tempURL = properties.getProperty("GetImageTempURL");
        filePrefix = properties.getProperty("GetImageFilePrefix");
        BASESQL_SELECT = properties.getProperty("GetImageBASESQL_SELECT");
        BASESQL_FROM = properties.getProperty("GetImageBASESQL_FROM");
        BASESQL_WHERE = properties.getProperty("GetImageBASESQL_WHERE");
        COLOURCGIDIRURL=properties.getProperty("COLOURCGIDIRURL");
        WSACGIDIRURL=properties.getProperty("WSACGIDIRURL");
        if (WSACGIDIRURL == null) {
            WSACGIDIRURL=WSAHTMLSchema.baseCGIURL;
        }
        //connMgr = DBConnectionManager.getInstance(); // previous connection manager
        /* no longer using connection pool as different logins required
        try {
            myBroker = new DbConnectionBroker(
                    "com.microsoft.jdbc.sqlserver.SQLServerDriver",
                    "jdbc:microsoft:sqlserver://" + server
                            + ":1433;DatabaseName=" + public_database, user, passwd,
                    2, 10, poolLogfile, 0.25, false, 300, 1);
        } 
        catch (IOException e) {
            logger.error(e);
        }
        */

    }

    static {

        try {
            Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
            Class.forName("net.sourceforge.jtds.jdbc.Driver");
        } catch (ClassNotFoundException e) {
            // A class not found error means the SQL driver class could not be
            // found.
            // Which means that this driver would not be available until this is
            // remedied. This flag variable will signal this to the class!

            logger.error("GetImage, Could not load SQLServerDriver class!");
        }
        // originally need to load jni library but the libary is in the java path
        //System.out.println(System.getProperty("java.library.path"));

        //System.loadLibrary("libjniast.so");
    }

    public void doGet(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // get seesion and see if user logged in
        boolean loginboolean=false;
        res.setBufferSize(8192*100);
        HttpSession session = req.getSession();
        String archive="WSA";
        
        if (req.getParameter("archive") != null) {
            archive=req.getParameter("archive");
        }
        logger.info("getObject "+archive);
        
        Enumeration eP= req.getParameterNames();
        String oURL=req.getRequestURL()+"?";
        StringBuffer urlSB=new StringBuffer(oURL);
        String eParam=null;
        while (eP.hasMoreElements()) {
        	eParam=(String)eP.nextElement();
        	urlSB.append(eParam);
        	urlSB.append("=");
        	urlSB.append(req.getParameter(eParam));
        	urlSB.append("&");
        }
        logger.info("URL: "+urlSB);
    
    
        int archiveID=VDFSSchema.getArchiveID(archive);
        String community=VDFSSession.getCommunity(session,archiveID);
        String [] servers = VDFSSession.getServers(community,archive,WSASERVERS,WSACUSERVERS,VSASERVERS,VSACUSERVERS,WSANSSERVERS);
        logger.info("getObject servers[0]: "+servers[0]);
      
        try {
            loginboolean=VDFSSession.getLoginBoolean(session,archive);
            }
            catch (Exception e){
                loginboolean=false;
            }
            String userSess=VDFSSession.getUser(session,archiveID,false);//(String)session.getAttribute("user");
            String genUser=VDFSSession.getUser(session,archiveID,true);
            String communitySess=VDFSSession.getCommunity(session,archiveID);//(String)session.getAttribute("community");
         
           
        
        StringBuffer select = new StringBuffer(BASESQL_SELECT);
        StringBuffer from = new StringBuffer(BASESQL_FROM);
        StringBuffer where = new StringBuffer(BASESQL_WHERE);
        
       
        int doTargetID=0;
        int doPosition=0;
        int doCName=0;
        Point2D.Double pointJ2000=null;
        boolean proceed=true;
        boolean doForce=true;

        res.setContentType("text/html");
        
        PrintWriter out = res.getWriter();

        

        Calendar rightNow=Calendar.getInstance();
        String uniqID = 
                  String.valueOf(rightNow.get(Calendar.MINUTE))
                + String.valueOf(rightNow.get(Calendar.DAY_OF_MONTH)+rightNow.get(Calendar.HOUR_OF_DAY))        
                +"_"
                + String.valueOf(rightNow.get(Calendar.MILLISECOND))
                +"_"
                + String.valueOf(rightNow.get(Calendar.SECOND))        
                + "_"+ getNextRunNumber();
        
        
        StringBuffer errorMessage = new StringBuffer("");
        String outputMessage = "";

        String database=req.getParameter("database");
        
        if (database !=null && database.equalsIgnoreCase("none")) {
            proceed=false;
            errorMessage.append("<b>Error: No valid database.</b><br>");
        }
        //name=&ra=&archive=OSA&targetID=&dec=&radius=1&cName=&database=gesiDR1&sys=J
        String targetID=null;
        if (req.getParameter("targetID") !=null && !req.getParameter("targetID").isEmpty()) {
        	targetID=req.getParameter("targetID");
        }
      
        long iTargetID=-9999;
        
        if (targetID !=null) {
        	try {
        	iTargetID=Long.valueOf(targetID).longValue();
        	doTargetID=1;
        	}
        	catch (Exception e) {
        		proceed=false;
        		errorMessage.append("<b>Error: supplied targetID is not an integer.</b><br>");
        		
			}
        }
        
        String cName=null;
        if (req.getParameter("cName") !=null && !req.getParameter("cName").isEmpty()) {
        	cName=req.getParameter("cName");
        }
        if (cName != null) {
        	doCName=1;
        }
        
        WorldCoords wc =new WorldCoords();
        String ra=null;
        String dec=null;
        int doCoords=0;
        String radius=null;
        String sys=null;
        double radiusD=0.0;
        
        if (req.getParameter("ra") !=null && !req.getParameter("ra").trim().isEmpty()) {
        	ra=req.getParameter("ra");
        }
        if (req.getParameter("dec") !=null && !req.getParameter("dec").trim().isEmpty()) {
        	dec=req.getParameter("dec");
        }
        if (req.getParameter("radius") !=null && !req.getParameter("radius").trim().isEmpty()) {
        	radius=req.getParameter("radius");
        	try {
            radiusD=Double.parseDouble(radius);
        	} catch (Exception e){
        		proceed=false;
        		errorMessage.append(" Unable to parse supplied radius<p>.");
        	}
        }
        if (req.getParameter("sys") !=null && !req.getParameter("sys").isEmpty()) {
        	sys=req.getParameter("sys");
        }
        
        if (ra!=null && dec !=null && radius!=null) {
        	try {
        		wc = new WorldCoords(Double.parseDouble(ra),Double.parseDouble(dec));
        		}
        		catch (Exception e){
        			try {
        				wc = new WorldCoords(ra,dec);
        			}
        			catch (Exception ane) {	   
        			    proceed = false;
        		 		errorMessage.append(" Unable to parse supplied coords<p>.");
        					 }
        				 }
        	 if (wc.getRaDeg() < 0) {
           	     proceed = true;
           	     errorMessage.append("<br>Supplied RA/Longitude &lt; 0");
           	 }
           	 if (wc.getRaDeg() > 360) {
           	     proceed = true;
           	     errorMessage.append("<br>Supplied RA/Longitude &gt; 0");
           	 }
           	 
           	 if (wc.getDecDeg() < -90) {
           	     proceed = true;
           	     errorMessage.append("<br>Supplied Dec/Latitude &lt; -90");
           	 }
           	 if (wc.getDecDeg() > 90) {
           	     proceed = true;
           	     errorMessage.append("<br>Supplied Dec/Latitude &gt; +90");
           	 }

           	 
            pointJ2000=new Point2D.Double(wc.getX(),wc.getY());
           	if (sys.equals("G")){
          wcscon.gal2fk5(pointJ2000);
          }
          if (sys.equals("B")){
          wcscon.fk425(pointJ2000);
          }  

          String ra2000=String.valueOf(pointJ2000.getX());
          String dec2000=String.valueOf(pointJ2000.getY());
          
          ra2000=ra2000.replace('+',' ');
          dec2000=dec2000.replace('+',' ');
          logger.info("GetObj "+ra2000+" "+dec2000+" "+ra+" "+dec+" "+radius);
          
          if (proceed && pointJ2000!=null) {
        	  doCoords=1;
          }
        }
        

   	
        
        Connection con = null;
        ResultSet rs = null;
        Statement stmt=null;
        PreparedStatement pStmt=null;
       
        
        out.println(HTMLSnippets.DOCTYPE);
        
        
        out.println("<HTML><HEAD>");
        out.println("<meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\">");
        out.println("<title>GetObject</title>");
        out.println("<style type=\"text/css\">");
        out.println(".js #target {display: none;}");
        out.println(".js #aa {display: none;}");
        out.println(".js #tTitle {display: none;}");
        out.println(".js #aaTitle {display: none;}");
        out.println("</style>");
        out.println("<style type=\"text/css\" title=\"currentStyle\">" +
        		"			@import \""+GESHTMLSchema.baseURL+"/common/DataTables/media/css/demo_page.css\"; " +
        //				"   @import \""+GESHTMLSchema.baseURL+"/common/DataTables/media/css/header.ccss\";" +
        		"			@import \""+GESHTMLSchema.baseURL+"/common/DataTables/media/css/demo_table.css\";		</style>");
        out.println("<script type=\"text/javascript\" charset=\"utf-8\" src=\""+GESHTMLSchema.baseURL+"/common/DataTables/media/js/jquery.js\"></script>");
        out.println("<script type=\"text/javascript\" charset=\"utf-8\" src=\""+GESHTMLSchema.baseURL+"/common/DataTables/media/js/jquery.dataTables.js\"></script>");
        out.println("<script type=\"text/javascript\" charset=\"utf-8\" src=\""+GESHTMLSchema.baseURL+"/common/DataTables/extras/FixedColumns/media/js/FixedColumns.js\"></script>");
        out.println("<script type=\"text/javascript\" charset=\"utf-8\" src=\""+GESHTMLSchema.baseURL+"/common/DataTables/media/js/sortPlugin.js\"></script>");

        out.println("<script type=\"text/javascript\">");
        out.println("      $('html').addClass('js');");
        out.println("</script>");
        /*
        out.println("<script type=\"text/javascript\" charset=\"utf-8\">"); 
        		out.println("	$(document).ready( function () {");
        		out.println("  var oTable = $('#target').dataTable( { ");
        		out.println("	\"sScrollX\": \"100%\",");
        	  //  out.println("	\"sScrollXInner\": \"140%\",");
        		out.println("	\"bScrollCollapse\": true");
        		out.println("} );");
        		out.println("new FixedColumns( oTable, {");
        	    out.println("	\"iLeftColumns\": 2,");
        	    out.println("	\"iLeftWidth\": 350");
        		out.println("} );");
        	    out.println("} );");
        		out.println("</script>");
        		*/
        /*
         * 
         * 
         * 
         * <head>
		
		
		
	</head>
         */
        out.print("</HEAD><body>");
    //    out.print("here");
        out.flush();
        res.flushBuffer();
      
        String mode="";
        if (req.getParameter("mode") != null){
            mode=req.getParameter("mode");
        }
        String programmeID="all"; // default was null
        String programmeStr=VDFSSchema.getAllSurveys(archiveID) ;// default
        
        
        
        if ((community.equalsIgnoreCase("nonSurvey") || VDFSSchema.isProprietary(community,archiveID))&& VDFSSession.getLoginBoolean(session,archive)) {
            programmeID=VDFSSession.getProgID(session,archiveID);
           // out.print(programmeID);
        }
        else {
            if (req.getParameter("programmeID") != null && !communitySess.equalsIgnoreCase("nonSurvey") && !VDFSSchema.isProprietary(communitySess,archiveID)){
                programmeID=req.getParameter("programmeID");
                if (!programmeID.equals("all")){
                    try {
                        programmeStr=VDFSSchema.getSurveyName(Integer.valueOf(programmeID).intValue(),archiveID);
                        }
                        catch (NumberFormatException nfe) {
                            proceed=false;
                            errorMessage.append("<br><b>Invalid programmeID.</b>");
                        }
            }
        }
        }

        if (communitySess != null && (communitySess.equalsIgnoreCase("nonSurvey") || VDFSSchema.isProprietary(communitySess,archiveID))) {
            
            try {
                int iPID=Integer.valueOf(programmeID).intValue();
                if (iPID <1000 && (archiveID==VDFSSchema.VSAARCHIVEID || archiveID==VDFSSchema.OSAARCHIVEID)) {
                    programmeStr=VDFSSchema.getSurveyName(iPID,archiveID);
                }
                else {
                programmeStr=userSess;
                }
                }
                catch (NumberFormatException nfe) {
                    programmeStr=userSess;
                }
            
            
        }
        
     
        
 
        
        out.println ("<h3>GetObject results</h3>");
        
        if (doTargetID+doCName+doCoords >1) {
        	proceed=false;
        	errorMessage.append(" <p>Please only supply one of either coordinates, targetID or cName ");
        }
        
        if (!proceed){
            out.println(errorMessage);
            out.println("<p><b>Query stopped: check warnings above and try again.</b>");
            return;
        }
         
        
          
     
 
        
        out.println("<br>Querying ...");
        res.flushBuffer();
        out.flush();
        res.flushBuffer();
       
        

        
        
        try {
            logger.info("GetObject,Login,"+userSess+","+communitySess+","+req.getRemoteAddr()+","+programmeID);
           
            out.println("<br>Connecting to database: "+database+"<p>");
            logger.info("GETIMAGE getting connection");
            
            if (archiveID==VDFSSchema.VSAARCHIVEID && VSASchema.isProprietary(community) &&
                    (database.equalsIgnoreCase(VSASchema.rollingDB) || database.equalsIgnoreCase(VSASchema.PRERELEASEDATABASE))) {
                database=VSASchema.actualRollingDB;
              
            }
            if (archiveID==VDFSSchema.OSAARCHIVEID && OSASchema.isProprietary(community) &&
                    (database.equalsIgnoreCase(OSASchema.rollingDB) || database.equalsIgnoreCase(OSASchema.PRERELEASEDATABASE))) {
                database=OSASchema.actualRollingDB;
              
            }
            
            con=DatabaseConnection.getConnection(servers,database,archive,session);
            servers=null;
            
             // con = DriverManager.getConnection(durl);
            if (con == null) {
                out.println("Can't get connection");
                return;
            }
            

            
            
            
            ResultSetMetaData md = null;
            
            try {
                stmt = con.createStatement();
                logger.info("GetObject created stmt.");
     
                
                if (doTargetID==1) {
                 pStmt=con.prepareStatement("select * from target where targetID = ? order by targetID");
                 pStmt.setLong(1, iTargetID);
                }
                
                
                if (doCName==1) {
                 pStmt=con.prepareStatement("select * from target where cName like ? order by targetID");
                 pStmt.setString(1, "%"+cName.trim()+"%");
                }
                
                if (doCoords==1) {
                	double minDec=pointJ2000.getY()-radiusD/60;
                	double maxDec=pointJ2000.getY()+radiusD/60;
                	pStmt=con.prepareStatement("select * from target where dec between ? and ?" +
                			" and 60.0*2.0*degrees(asin(sqrt(square(sin(radians(0.5*(?-dec)))) + cos(radians(?))*cos(radians(dec))* square(sin(radians(0.5*(?-ra))))))) < ?" +
                			" order by targetID	");
                	pStmt.setDouble(1, minDec);
                	pStmt.setDouble(2, maxDec);
                	pStmt.setDouble(3, pointJ2000.getY());
                	pStmt.setDouble(4, pointJ2000.getY());
                	pStmt.setDouble(5, pointJ2000.getX());
                	pStmt.setDouble(6, radiusD);
                	logger.info("min/max dec: "+minDec+" "+maxDec);
                }
                
                /*
                 * 
                 * 
                 * 60.0*2.0*degrees(asin(sqrt(square(sin(radians(0.5*(@dec1-@dec2)))) + cos(radians(@dec1))*cos(radians(@dec2))* square(sin(radians(0.5*(@ra1-@ra2))))))
                 */
                String SQL=null;
           
                logger.info(pStmt);
                rs = pStmt.executeQuery();
                md = rs.getMetaData();

                int row = 0;
                int noCols=md.getColumnCount();
                String [] strArray= new String [noCols];
                
                FormatRS frs=new FormatRS();
                frs.setRSMD(md);
                StringBuffer rowSB=new StringBuffer("");
                boolean moreThanOne=false;
                
                
                
                   out.flush();
                   res.flushBuffer();
                   
/*
                   out.println("<script type=\"text/javascript\">");
                   out.println("$(document).ready(function() {");
                   out.println("var oTable = $('#target').dataTable();");
                   out.println("oTable.fnSetColumnVis( 3, false ); console.log(\"here\"); } ) </script> ");
                   */
                StringBuffer targetTableSB=new StringBuffer("");
                StringBuffer targetHeaderSB=new StringBuffer("");
                StringBuffer targetDataSB=new StringBuffer("");
                
                targetTableSB.append("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"target\">");
            	
            	
            	int targetIDCol=0;
            	for (int i=0; i<noCols; i++) {
            		if (md.getColumnName(i+1).equalsIgnoreCase("targetID")) {
            			targetIDCol=i+1;
            		}
            	}
            	
               
            	long  tID=0L;
            	
            	String trClass="<tr class=\"getO\">";
                
            	while (rs.next()) {
                	tID=rs.getLong(targetIDCol);
                	rowSB.append(trClass);
                	row++;
                	if (row > 1) {
                		moreThanOne=true;
                	}
                	if (moreThanOne && row==2){
                		rowSB.insert(trClass.length(),"<td><a target=\"_blank\" href=\""+oURL +
                				"archive=GES&database="+database+"&targetID="+tID+"\">link</a></td>");
                		targetDataSB.append(rowSB);
                		//out.flush();
                		rowSB.setLength(0);                		
                	}
                	if (moreThanOne) {
                		rowSB.append("<td><a target=\"_blank\" href=\""+oURL +
                				"archive=GES&database="+database+"&targetID="+tID+"\">link</a></td>");
                	}
                	strArray=frs.setRS(rs);
                	for (int i=0; i<noCols;i++) {
                		rowSB.append("<td>"+strArray[i].trim()+"</td>");
                		//targetTableSB.append(strArray[i]+",");
                	}
                	rowSB.append("</tr>\n");
                }
                
                if (!moreThanOne && row >0) {
                	rowSB.insert(trClass.length(),""); //"<td>noLink</td>");
                }
                targetDataSB.append(rowSB);  
                
                
                
             	targetHeaderSB.append("<thead><tr>");
             	if (moreThanOne) {
             		targetHeaderSB.append("<th>link</th>");
             			}
             
            	for (int i=0; i<noCols; i++) {
            		targetHeaderSB.append("<th>"+md.getColumnName(i+1)+"</th>");
            	}
            	targetHeaderSB.append("</tr></thead><tbody>");
            	
            	targetTableSB.append(targetHeaderSB);
            	targetTableSB.append(targetDataSB);
                targetTableSB.append("</tbody>");
                
                targetTableSB.append("</table>");  
                
                int noFixedCols=2;
                
                
                
                out.println("<script type=\"text/javascript\">");
                out.println("$(document).ready(function() {");
                out.println("$('#tTitle').show();");
                out.println("$('#target').show();");
                out.println("  var oTable = $('#target').dataTable( { ");
                //out.println(" \"sDom\": 'l<\"header\">frtip',");

                out.println("\"aoColumns\": [");
                if (moreThanOne) {
                out.println("null,");
                noFixedCols=3;
                }
                for (int i=0; i<noCols; i++) {
                	if (JDBCDataTypes.isNumeric(md.getColumnType(i+1))){
            	//	if (md.getColumnName(i+1).equalsIgnoreCase("dec")){
            			out.print("{ \"sType\": \"scientific\" }");
            	} else {
            		out.print("null");
            	}
            		if (i+1<noCols) {
            			out.print(",");
            		}
            		out.print("\n");
                }
            		out.println("],");
            		
        		out.println("	\"sScrollX\": \"100%\",");
        	  //  out.println("	\"sScrollXInner\": \"140%\",");
        		out.println("	\"bScrollCollapse\": true");
        		out.println("} );");
        		out.println("new FixedColumns( oTable, {");
        	    out.println("	\"iLeftColumns\": "+noFixedCols+",");
        	    //out.println("	\"iLeftWidth\": 50");
        		out.println("} );");
        	    //out.println("} );");
        		/*
                out.println("$('#target').dataTable( {");
                out.println("\"aoColumns\": [");
                for (int i=0; i<noCols; i++) {
            		if (md.getColumnName(i+1).equalsIgnoreCase("dec")){
            			out.print("{ \"sType\": \"scientific\" }");
            	} else {
            		out.print("null");
            	}
            		if (i+1<noCols) {
            			out.print(",");
            		}
            		out.print("\n");
                }
            		out.println("]");
            		out.println("} );");
            		*/
        		//out.println("$(\"div.header\").html('<b>Custom tool bar! Text/images etc.</b>');");
                   out.println("} );");
                   
                   out.println("</script>");
                
                   out.println("<div id=\"tTitle\"><p><h3> Target table </h3> <p></div>");             
                if (row >0) {
                	out.println("<div id=\"table1\">");
                out.println(targetTableSB);
                out.println("</div>");
                }
                else {
                	out.println("no results");
                }
                
                frs=null;
                
                if (!moreThanOne) {
                	pStmt=con.prepareStatement("select * from AstroAnalysis where targetID = ?");
                    pStmt.setLong(1, tID);
                    rs=pStmt.executeQuery();
                    md=rs.getMetaData();
                    String [] aaArray= new String [md.getColumnCount()];                   
                    FormatRS ars=new FormatRS();
                    ars.setRSMD(md);
                    
                    rowSB.setLength(0);
                    StringBuffer aaData=new StringBuffer("");
                    StringBuffer aaHeader=new StringBuffer("");
                    StringBuffer aaTable=new StringBuffer("");
                    aaHeader.append("<thead><tr>");
                 	
                	for (int i=0; i<md.getColumnCount(); i++) {
                		aaHeader.append("<th>"+md.getColumnName(i+1)+"</th>");
                	}
                	aaHeader.append("</tr></thead><tbody>");
                	//out.println("here "+tID);
                	out.flush();
                	res.flushBuffer();
                
                    row=0;
                    while (rs.next()) {
                    	
                    	rowSB.append(trClass);
                    	row++;
                    	aaArray=ars.setRS(rs);
                    	for (int i=0; i<md.getColumnCount();i++) {
                    		rowSB.append("<td>"+aaArray[i].trim()+"</td>");
                    		//targetTableSB.append(strArray[i]+",");
                    	}
                    	rowSB.append("</tr>\n");
                    }
                    aaTable.append("<table cellpadding=\"0\" cellspacing=\"0\" border=\"0\" class=\"display\" id=\"aa\">");
                    aaTable.append(aaHeader);
                    aaTable.append(rowSB);
                    aaTable.append("</tbody>");
                    aaTable.append("</table>");
                    
                    out.println("<script type=\"text/javascript\">");
                    out.println("$(document).ready(function() {");
                    out.println("$('#aaTitle').show();");
                    out.println("$('#aa').show();");
                    out.println("  var aaTable = $('#aa').dataTable( { ");
                    
                    out.println("\"aoColumns\": [");
                   
                    for (int i=0; i<md.getColumnCount(); i++) {
                    	if (JDBCDataTypes.isNumeric(md.getColumnType(i+1))){
                	//	if (md.getColumnName(i+1).equalsIgnoreCase("dec")){
                			out.print("{ \"sType\": \"scientific\" }");
                	} else {
                		out.print("null");
                	}
                		if (i+1<md.getColumnCount()) {
                			out.print(",");
                		}
                		out.print("\n");
                    }
                		out.println("],");
                		
            		out.println("	\"sScrollX\": \"100%\",");
            	  //  out.println("	\"sScrollXInner\": \"140%\",");
            		out.println("	\"bScrollCollapse\": true");
            		out.println("} );");
            		out.println("new FixedColumns( aaTable, {");
            	    out.println("	\"iLeftColumns\": "+noFixedCols+",");
            	    //out.println("	\"iLeftWidth\": 50");
            		out.println("} );");
            	    //out.println("} );");
            		/*
                    out.println("$('#target').dataTable( {");
                    out.println("\"aoColumns\": [");
                    for (int i=0; i<noCols; i++) {
                		if (md.getColumnName(i+1).equalsIgnoreCase("dec")){
                			out.print("{ \"sType\": \"scientific\" }");
                	} else {
                		out.print("null");
                	}
                		if (i+1<noCols) {
                			out.print(",");
                		}
                		out.print("\n");
                    }
                		out.println("]");
                		out.println("} );");
                		*/
                       out.println("} );");
                       out.println("</script>");
                    
                    
                    out.println("<div class=\"dataTables_info\" id=\"aaTitle\"><p><h3>AstroAnalysis table</h3></p></div>"); 
                    out.println("<div id=\"table2\">");
                    out.println(aaTable);
                    out.println("</div>");
                    
                    
                    noFixedCols=2;
                    
                    
                    
                    
                	
                	
                }
               out.println("</body></html>");
               out.flush();
               res.flushBuffer();
               
               out.close();
               
            } catch (SQLException se) {
                out.println("<p>Error querying the database: "
                        + se.getErrorCode() + se);

                if (se.getErrorCode() == 0) {
                    con.close();
                }
            }
            

            catch (Exception e) {
                out.println("<p>Error "+e);
                System.out.println(e);
                //e.printStackTrace(out);
            }


        } 
        
        catch (SQLException se) {
            out.println("<p>Error querying the database, unable to get connection ");
            logger.error("GetImage,"+se);
        }
        
        
        catch (Exception e) {
            logger.error("GetImage,"+e);
           // System.out.println("errorher");
           // System.out.println(e);
           // e.printStackTrace(out);
  
        } finally {

            
            System.gc();
            //System.out.println("gc called");
            //out.flush();
            //out.close();
            try {
                //Thread.	(6000);
            	logger.info("GetObj closing");
            	pStmt.close();
                stmt.close();

            } catch (Exception e) {
                ;
            }
            if (con != null) {

                
                //	connMgr.freeConnection("idb", con);
              //  myBroker.freeConnection(con);
                try {
                	logger.info("GetObj connection closing");
                    con.close();
                    con=null;
                    stmt=null;
                    rs=null;
                }
                catch (Exception e) {
                    ;
                }    

                
            }

        } // finally

    } // doGet

    public void destroy() {
        //          connMgr.release();
        //myBroker.destroy();
        logger=null;
        super.destroy();
    }

    protected void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        // Data received by an HTTP POST is handled the same way
        // as data sent with a HTTP GET request... simply pass on to above...
        doGet(req, res);
    }; // END of doPost()

    protected boolean imageExtract(String[] strArray, String uniqName) {
        String baseFitsFileName = filePrefix + strArray[0];
        String outFitsFileName=tempPath + uniqName + ".fits.gz";
        String outJpegFileName=tempPath + uniqName + ".jpg";
        String errorMessage = "";
        String outputMessage = "";
        File baseFitsFile = new File(baseFitsFileName);
        File JPEGFile;
        if (baseFitsFile.exists()) {
            try {
               // System.out.println("file exists");
                Runtime rt = Runtime.getRuntime();
                String[] execStrArray1 = { progPath + "read_img.e",
                        baseFitsFileName, outFitsFileName, strArray[3], strArray[4],
                        strArray[5], strArray[6], strArray[7],
                        strArray[10] };   
                Process proc = rt.exec(execStrArray1);
                // any error message?
                StreamGobblerO errorGobbler = new StreamGobblerO(proc
                        .getErrorStream(), "ERROR");
                // any output?
                StreamGobblerO outputGobbler = new StreamGobblerO(proc
                        .getInputStream(), "OUTPUT");

                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                // any error???
                int exitVal = proc.waitFor();
                
                errorMessage = errorGobbler.getMessageBuffer();
                outputMessage = outputGobbler.getMessageBuffer();

  
                String[] execStrArray = { progPath + "fits2jpeg",
                        "-fits", outFitsFileName.trim() + "[1]", "-jpeg",
                        outJpegFileName };
                proc = rt.exec(execStrArray);
                // any error message?
                errorGobbler = new StreamGobblerO(proc.getErrorStream(),
                        "ERROR");

                // any output?
                outputGobbler = new StreamGobblerO(
                        proc.getInputStream(), "OUTPUT");

                // kick them off
                errorGobbler.start();
                outputGobbler.start();

                // any error???
                exitVal = proc.waitFor();
               // System.out.println("ExitValue: " + exitVal);
                errorMessage = errorGobbler.getMessageBuffer();                
                outputMessage = outputGobbler.getMessageBuffer();
                JPEGFile = new File(outJpegFileName);
                if (JPEGFile.exists()) {
                    return true;
                    }
            }
                catch (Exception e) {
                    return false;
                }
        }
        else {
            return false;
        }
        return false;
    }
}

class StreamGobblerO extends Thread {
    InputStream is;

    String type;

    OutputStream os;

    StringBuffer messageBuffer = new StringBuffer("a");

    StreamGobblerO(InputStream is, String type) {
        this(is, type, null);
    }

    StreamGobblerO(InputStream is, String type, OutputStream redirect) {
        this.is = is;
        this.type = type;
        this.os = redirect;
    }

    public synchronized void run() {
        try {
            PrintWriter pw = null;
            if (os != null)
                pw = new PrintWriter(os);

            InputStreamReader isr = new InputStreamReader(is);
            BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (pw != null)
                    pw.println(line);
                messageBuffer.append(line);
                //System.out.println(messageBuffer.toString());
            }
            if (pw != null)
                pw.flush();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
        // System.out.println(messageBuffer.toString());
    }

    public synchronized String getMessageBuffer() {
        return messageBuffer.toString();
    }
}

