/******************************************************************************
*
* Copyright: Intellectual Property of Four Elements Capital Pte Ltd, Singapore.
* All rights reserved.
*
******************************************************************************/

package com.fourelementscapital.db.mariadb;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Vector;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;

import com.fourelementscapital.db.GeneralUtilDB;
import com.fourelementscapital.db.SchedulerDB;
import com.fourelementscapital.db.vo.SchedulerTrigger;

/**
 * Scheduler MariaDB DAO implementation
 */	
public class SchedulerDBMariaDB extends SchedulerDB {	 
	
	
	private Logger log=LogManager.getLogger(SchedulerDBMariaDB.class.getName());	
	
	
	/**
	 * {@inheritDoc}
	 */		
	public List listScheduler() throws Exception {
		

		StringBuffer sb = new StringBuffer();
		sb.append("Select a.*,b.folder_name,c.tagname as owner_tag,(select CONCAT(GROUP_CONCAT(cast(tags.tagname as CHAR(8000)) order by tags.tagname SEPARATOR ', '), ', ') from scheduler_tags as st  left outer join tags on tags.id=st.tag_id WHERE st.scheduler_id=a.id ) as stags "); 
		sb.append("FROM scheduler as a ");
		sb.append("LEFT join scheduler_folder as b on a.folder_id=b.id ");
		sb.append("left join tags as c on c.id=a.owner_tag_id ");
		sb.append("WHERE  a.deleted IS NULL OR a.deleted<>1 ");  
		sb.append("ORDER by a.name ");
		
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		
		ResultSetMetaData metaData = rs.getMetaData();
		int colCount = metaData.getColumnCount();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	/**
	 * {@inheritDoc}
	 */		
	public List listSchedulerTaskUIDJoin() throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("Select a.*,b.folder_name,c.tagname as owner_tag,(select CONCAT(GROUP_CONCAT(cast(tags.tagname as CHAR(8000)) order by tags.tagname SEPARATOR ', '), ', ') from scheduler_tags as st  left outer join tags on tags.id=st.tag_id   where st.scheduler_id=a.id ) as stags ");
		sb.append("from scheduler as a ");
		sb.append("left outer join scheduler_folder as b on a.folder_id=b.id AND a.taskuid = b.taskuid ");
		sb.append("left outer join tags as c on c.id=a.owner_tag_id ");
		sb.append("WHERE a.deleted IS NULL OR a.deleted<>1 ");
		sb.append("order by a.name ");	
		
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());

		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}

		rs.close();
		ps.close();
		return rtn;
	}

	
	/**
	 * {@inheritDoc}
	 */			
	public void fixSchBrokenFolders() throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("update scheduler set folder_id=0 where id in ( select id from ( ");
		sb.append("select a.id from scheduler as a ");
		sb.append("left outer join scheduler_folder as f on a.folder_id = f.id and a.taskuid = f.taskuid ");
		sb.append("where f.folder_name is null and a.folder_id >0 ) temp_table ) ");
		
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ps.executeUpdate();
		ps.close();
		
	}
	
	
	/**
	 * {@inheritDoc}
	 */			
	public List listScheduler(List<String> themetags) throws Exception {
		    String thms="";	
		    for(String tg:themetags){
		    	thms+=(thms.equals(""))?"'thm-"+tg+"'":",'thm-"+tg+"'";
		    }
		 
		    log.debug("thms:"+thms);
		    
			StringBuffer sb = new StringBuffer();
			sb.append("Select a.*,b.folder_name,c.tagname as owner_tag,(select CONCAT(GROUP_CONCAT(cast(tags.tagname as CHAR(8000)) order by tags.tagname SEPARATOR ', '), ', ') from scheduler_tags as st  left outer join tags on tags.id=st.tag_id   where st.scheduler_id=a.id ) as stags ");
			sb.append("from scheduler as a ");
			sb.append("left outer join scheduler_folder as b on a.folder_id=b.id AND a.taskuid = b.taskuid ");
			sb.append("left outer join tags as c on c.id=a.owner_tag_id ");
			sb.append("WHERE (a.deleted IS NULL OR a.deleted<>1 ) ");
			if(!thms.equals("")){
				sb.append("AND a.id IN(select scheduler_id from scheduler_tags as a1   left outer join tags as a2 on a1.tag_id = a2.id  where a2.tagname in ("+thms+")) ");
			}else{
				sb.append("AND a.id=0 ");
			}
			sb.append("order by a.name ");
			
			log.debug("query:"+sb.toString());
			PreparedStatement ps=this.connection().prepareStatement(sb.toString());
			
			//ps.setString(1, following_user);
			ResultSet rs=ps.executeQuery();
			Vector rtn=new Vector();
			while(rs.next()){			
				//rtn.add(new BasicRowProcessor().toMap(rs));
				rtn.add(GeneralUtilDB.resultsetToMap(rs));
			}
			//added by rams on 5-june-2012
			rs.close();
			ps.close();
			return rtn;
	 }

	
	/**
	 * {@inheritDoc}
	 */		
	public List listTrashedScheduler() throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("SELECT a.*,IFNULL(TIMESTAMPDIFF(day,date(a.deletedon),now()),7) as deleteddays,b.folder_name,(select CONCAT(GROUP_CONCAT(cast(tags.tagname as CHAR(8000)) order by tags.tagname SEPARATOR ', '), ', ') from scheduler_tags as st  left outer join tags on tags.id=st.tag_id WHERE st.scheduler_id=a.id ) as stags ");
		sb.append("FROM scheduler as a ");
		sb.append("LEFT outer join scheduler_folder as b on a.folder_id=b.id ");
		sb.append("WHERE  a.deleted=1 ");
		sb.append("ORDER by a.deletedon DESC ");
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){		
			//Map d=new BasicRowProcessor().toMap(rs);
			Map d = GeneralUtilDB.resultsetToMap(rs);
			
			Object dd=d.get("deletedon");
			if(dd!=null){
				SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM-yyyy HH:mm");
				d.put("deletedon_format", sdf.format((Date)dd));	
			}
			rtn.add(d);
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */		
	public List searchScheduler(String ids) throws Exception {
		
		Vector rtn=new Vector();

		String query="Select a.*,b.folder_name from scheduler as a left outer join scheduler_folder as b on a.folder_id=b.id ";
		query+=" WHERE a.id IN("+ids+") ";				
		query+=" AND  (a.deleted IS NULL OR a.deleted<>1) "; //added by rams to support trash bin feature.
		PreparedStatement ps=this.connection().prepareStatement(query);			
		ResultSet rs=ps.executeQuery();			
		while(rs.next()){			
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		rs.close();
		ps.close();

		return rtn;		
	}
	
	/**
	 * {@inheritDoc}
	 */		
	public boolean isDeleted(int id) throws Exception {

		boolean result = false;
		String query="Select deleted from scheduler WHERE id="+id;				
		PreparedStatement ps=this.connection().prepareStatement(query);			
		ResultSet rs=ps.executeQuery();			
		while(rs.next()){			
			if (rs.getInt("deleted") == 1) {
				result = true;
			}
		}
		rs.close();
		ps.close();
		return result;		
	}	
	
	
	/**
	 * {@inheritDoc}
	 */		
	public List listAllTasksByUID(String taskuid) throws Exception {

		String query="SELECT a.*,b.folder_name FROM scheduler AS a LEFT OUTER JOIN scheduler_folder AS b ON a.folder_id=b.id ";
		query+=" WHERE a.taskuid=? ";
		query+=" AND  (a.deleted IS NULL OR a.deleted<>1) "; //added by rams to support trash bin feature.
		query+=" ORDER BY a.name ";
		
		PreparedStatement ps=this.connection().prepareStatement(query);
		ps.setString(1, taskuid);
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */		
	public Map listSchedulerItem(long scheduler_id) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("SELECT a.*,b.folder_name FROM scheduler AS a LEFT OUTER JOIN scheduler_folder AS b ON a.folder_id=b.id where a.id=? ORDER BY a.name");
		ps.setLong(1, scheduler_id);
		ResultSet rs=ps.executeQuery();
		Map rtn=null;
		if(rs.next()){			
			//rtn=new BasicRowProcessor().toMap(rs);
			rtn = GeneralUtilDB.resultsetToMap(rs);
		}
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */			
	 public List folderTasks(int folder_id) throws Exception {
		
		String query="Select * from scheduler WHERE folder_id=? ";
		query+=" AND  (deleted IS NULL OR deleted<>1) ";

		PreparedStatement ps=this.connection().prepareStatement(query);
		ps.setInt(1, folder_id);
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}


		/**
		 * {@inheritDoc}
		 */			
	public List searchScheduler(String keyword, int tagid) throws Exception {		
		
		Vector rtn=new Vector();
		String query=null;
		if(keyword!=null && !keyword.equals("") && tagid>0) {			
			query="Select a.*,b.folder_name from scheduler as a left outer join scheduler_folder as b on a.folder_id=b.id WHERE a.name LIKE '%"+keyword+"%' AND a.id IN(select scheduler_id from scheduler_tags  WHERE tag_id="+tagid+") AND  (a.deleted IS NULL OR a.deleted<>1)";		
		}else if (keyword!=null && !keyword.equals("")){
			query="Select a.*,b.folder_name from scheduler as a left outer join scheduler_folder as b on a.folder_id=b.id WHERE a.name LIKE '%"+keyword+"%' AND  (a.deleted IS NULL OR a.deleted<>1)";
		}else if(tagid>0)  {
			query="Select a.*,b.folder_name from scheduler as a left outer join scheduler_folder as b on a.folder_id=b.id WHERE a.id IN(select scheduler_id from scheduler_tags  WHERE tag_id="+tagid+") AND  (a.deleted IS NULL OR a.deleted<>1)";
		}else{			
			query="Select a.*,b.folder_name from scheduler as a left outer join scheduler_folder as b on a.folder_id=b.id WHERE a.deleted IS NULL OR a.deleted<>1 ";
		}
		PreparedStatement ps=this.connection().prepareStatement(query);			
		ResultSet rs=ps.executeQuery();			
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}	
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;		
	}
	
	
	/**
	 * {@inheritDoc}
	 */		
	public boolean isNameExisting(String name,int scheduler_id) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("Select * FROM scheduler where name=? AND id<>?");
		ps.setString(1, name);
		ps.setInt(2, scheduler_id);		
		
		ResultSet rs=ps.executeQuery();
		
		boolean rtn=false;
		if(rs.next()){			
			rtn =true;
		} 
		rs.close();
		ps.close();
		return rtn;
		
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public List listOfFolders(String taskuid) throws Exception {
		
		PreparedStatement ps=null;
		if(taskuid!=null){
			ps=this.connection().prepareStatement("Select * FROM scheduler_folder where taskuid=? ORDER BY folder_name");
			ps.setString(1, taskuid);
		}else{
			ps=this.connection().prepareStatement("Select * FROM scheduler_folder ORDER BY folder_name");
		}
		
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}

	
	/**
	 * {@inheritDoc}
	 */			
	public List listofMyFolders(List<String> themetags) throws Exception {
		
		String thms="";	
	    for(String tg:themetags){
		    	thms+=(thms.equals(""))?"'thm-"+tg+"'":",'thm-"+tg+"'";
		}
		 
	    String query="";
	    query+="Select * FROM scheduler_folder WHERE id in(select folder_id from scheduler where id in( ";
        query+="  Select scheduler_id from scheduler_tags as a1 ";
        query+="  left outer join tags as a2 on a1.tag_id = a2.id ";
        if(thms!=null && !thms.equals("")){
        	query+="  where a2.tagname in ("+thms+") ) ";
        }else{
        	query+=" )";
        }
        query+=") ORDER BY folder_name ";
		PreparedStatement ps=this.connection().prepareStatement(query);

		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		 
		rs.close();
		ps.close();
		
		return rtn;
	}
 
	
	/**
	 * {@inheritDoc}
	 */		
	public String getFolderTaskUID(int folder_id) throws Exception {
		
		PreparedStatement ps=null;
		
		ps=this.connection().prepareStatement("Select taskuid FROM scheduler_folder where id=?");
		ps.setInt(1, folder_id);
		
		ResultSet rs=ps.executeQuery();
		String rtn=null;
		while(rs.next()){			
			rtn=rs.getString("taskuid");
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}


	/**
	 * {@inheritDoc}
	 */		
	public void updateTaskFolder(int scheduler_id,int folder_id) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("update scheduler SET folder_id=? where id=?");
		ps.setInt(1, folder_id);
		ps.setInt(2, scheduler_id);
		ps.executeUpdate();
		ps.close();		
		
		PreparedStatement ps1=this.connection().prepareStatement("update scheduler_taskdata SET val=? WHERE field_shortname=? AND scheduler_id=?");
		if(folder_id>0){
			ps1.setString(1, folder_id+"");
		}else{
			ps1.setString(1, "");
		}
		ps1.setString(2, "folder_id");
		ps1.setInt(3, scheduler_id);
		ps1.executeUpdate();
		ps1.close();
	}

	
	/**
	 * {@inheritDoc}
	 */		
	public void updateCallingAnotherScript(int scheduler_id, int calling_another_script /* either 1 or 0 */) throws Exception  {
		
		PreparedStatement ps=this.connection().prepareStatement("update scheduler SET calling_another_script=? WHERE id=?");
		ps.setInt(1, calling_another_script);
		ps.setInt(2, scheduler_id);		 	
		ps.executeUpdate();
	 
		ps.close();	
	}

	
	/**
	 * {@inheritDoc}
	 */		
	public void moveTasks(String d_tuid, int d_fid, String s_tuid, int s_fid) throws Exception  {
		
		PreparedStatement ps=this.connection().prepareStatement("update scheduler SET taskuid=?,folder_id=? WHERE taskuid=? AND folder_id=?");
		ps.setString(1, d_tuid);
		ps.setInt(2, d_fid);
		ps.setString(3, s_tuid);
		ps.setInt(4, s_fid);		
		ps.executeUpdate();
		
		PreparedStatement ps1=this.connection().prepareStatement("update scheduler_taskdata SET val=? WHERE field_shortname='folder_id' AND scheduler_id IN (SELECT id FROM scheduler WHERE folder_id=?)");		 
		ps1.setString(1, d_fid+"");		
		ps1.setInt(2, d_fid);		
		ps1.executeUpdate();
			
		ps1.close();
		ps.close();	
	}
	
	
	/**
	 * {@inheritDoc}
	 */			
	public void renameFolder(String taskuid, String oldname, String newname) throws Exception {		

        if(!oldname.equals(newname)){
        	checkFolderExisting(taskuid,newname);
        }
		PreparedStatement ps=this.connection().prepareStatement("update scheduler_folder set folder_name=replace(folder_name,?,?)  where (folder_name LIKE ? OR folder_name=?) AND taskuid=?");

		ps.setString(1, oldname);
		ps.setString(2, newname);
		ps.setString(3, oldname+"/%");
		ps.setString(4, oldname);
		ps.setString(5, taskuid);	

		ps.executeUpdate();
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */		
	public void moveItemToRootOrGroup(int scheduler_id, String taskuid, int folder_id) throws Exception {
				
		//PreparedStatement ps=this.connection().prepareStatement("update scheduler_folder set folder_name=replace(folder_name,?,?)  where (folder_name LIKE ?+'/%' OR folder_name=?) AND taskuid=?");
		
		this.connection().setAutoCommit(false);
        try{
			String query="UPDATE scheduler SET taskuid=?,folder_id=?  WHERE id=?";
			PreparedStatement ps=this.connection().prepareStatement(query);
			ps.setString(1,taskuid);
			ps.setInt(2,folder_id);		
			ps.setInt(3,scheduler_id);	
	 
			ps.executeUpdate();
			

			PreparedStatement ps1=this.connection().prepareStatement("update scheduler_taskdata SET val=? WHERE field_shortname=? AND scheduler_id=?");
			if(folder_id>0){
				ps1.setString(1, folder_id+"");
			}else{
				ps1.setString(1, "");
			}
			ps1.setString(2, "folder_id");
			ps1.setInt(3, scheduler_id);
			ps1.executeUpdate();
			ps1.close();
			
			this.connection().commit();
        }catch(Exception e){        	
        	this.connection().rollback();
        	throw e;
        }finally{        
        	this.connection().setAutoCommit(true);
        }
	}
	 
	
	/**
	 * {@inheritDoc}
	 */		
	public ArrayList<Integer> moveItems(String foldername, String taskuid, String parentfolder, String targetuid, String targetpath) throws Exception {
				
		//PreparedStatement ps=this.connection().prepareStatement("update scheduler_folder set folder_name=replace(folder_name,?,?)  where (folder_name LIKE ?+'/%' OR folder_name=?) AND taskuid=?");
	
		ArrayList rtn=new ArrayList();
		if(parentfolder!=null && !parentfolder.equals("") && !parentfolder.endsWith("/")){
			parentfolder+="/";
		}
		if(targetpath!=null && !targetpath.equals("") && !targetpath.endsWith("/")){
			targetpath+="/";
		}

		checkFolderExisting(targetuid, targetpath+foldername);
		
		this.connection().setAutoCommit(false);
        try{
        	
        	String wherecond="WHERE folder_id IN(SELECT id from scheduler_folder	WHERE (folder_name LIKE ?	OR folder_name=?)	AND taskuid=?)";
			
			
			PreparedStatement ps0=this.connection().prepareStatement("SELECT id from scheduler "+wherecond);
			ps0.setString(1,parentfolder+foldername+"/%");		
			ps0.setString(2,parentfolder+foldername);		
			ps0.setString(3,taskuid);
			ResultSet rs=ps0.executeQuery();
			while(rs.next()) {
				Integer id=rs.getInt("id");
				rtn.add(id);
			}
			rs.close();
			ps0.close();
			
			
			String query="UPDATE scheduler SET taskuid=? "+wherecond;
			PreparedStatement ps=this.connection().prepareStatement(query);
			ps.setString(1,targetuid);
			ps.setString(2,parentfolder+foldername+"/%");		
			ps.setString(3,parentfolder+foldername);		
			ps.setString(4,taskuid);
			ps.executeUpdate();
			
	        String query2="UPDATE scheduler_folder SET folder_name=replace(folder_name,?,?), taskuid=? WHERE (folder_name LIKE ? OR folder_name=?) AND taskuid=?";
	        PreparedStatement ps2=this.connection().prepareStatement(query2);
	        ps2.setString(1, parentfolder+foldername);
	        ps2.setString(2, targetpath+foldername);
	        ps2.setString(3, targetuid);
	        ps2.setString(4, parentfolder+foldername+"/%");
			ps2.setString(5, parentfolder+foldername);
			ps2.setString(6, taskuid);		
			ps2.executeUpdate();
			
			this.connection().commit();
			return rtn;
        }catch(Exception e){        	
        	this.connection().rollback();
        	throw e;
        }finally{        
        	this.connection().setAutoCommit(true);
        }
		
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void deleteFolder(int folderid) throws Exception {
		
		PreparedStatement ps0=this.connection().prepareStatement("select folder_name,taskuid from scheduler_folder where id=?");
		ps0.setInt(1, folderid);
		ResultSet rs0=ps0.executeQuery();
		try{
			if(rs0.next()){
				PreparedStatement ps1=null;
				ResultSet rs1=null;
				try{
					String foldername=rs0.getString("folder_name");
					String taskuid=rs0.getString("taskuid");
					ps1=this.connection().prepareStatement("select * from scheduler_folder where left(folder_name,length(?))=? AND id<>? AND taskuid=? ");
					ps1.setString(1, foldername);
					ps1.setString(2, foldername);
					ps1.setInt(3, folderid);
					ps1.setString(4, taskuid);			
					rs1=ps1.executeQuery();
					if(rs1.next()){				
						throw new Exception("You can't delete this folder as it has Sub folder:"+rs1.getString("folder_name")+". Please delete that first");		
					}
				}catch(Exception e){
					throw e;
				}finally{
					if(rs1!=null) rs1.close();
					if(ps1!=null) ps1.close();
				}
			}
		}catch(Exception e1){
			throw e1;
		}finally{
			rs0.close();
			ps0.close();
		}
		
		
		PreparedStatement ps=this.connection().prepareStatement("delete from scheduler_folder where id=?");		
		ps.setInt(1, folderid);
		ps.executeUpdate();
		
		PreparedStatement ps1=this.connection().prepareStatement("update scheduler SET folder_id=null where folder_id=?");		
		ps1.setInt(1, folderid);
		ps1.executeUpdate();
		ps1.close();
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public long addFolder(String taskuid,String foldername) throws Exception {
		
		checkFolderExisting(taskuid,foldername);
		
		long id=0;
		if(foldername.contains("/")){
			String[] folders=foldername.split("/");			
			String parent=foldername.substring(0,foldername.lastIndexOf(folders[folders.length-1]));
			if(parent.contains("/")){
				parent=parent.substring(0,parent.lastIndexOf("/"));
			}
			//throw new Exception("Parent folder:"+parent);
			PreparedStatement ps0=this.connection().prepareStatement("select folder_name from scheduler_folder WHERE folder_name=? AND taskuid=?");
			ps0.setString(1, parent);
			ps0.setString(2, taskuid);
			ResultSet rs0=ps0.executeQuery();
			if(!rs0.next()){
				throw new Exception("Parent folder:"+parent+" does not exist, Please create parent folder inclusive of all root folders");				
			}
		}
		
		PreparedStatement ps=this.connection().prepareStatement("insert into scheduler_folder(taskuid,folder_name) values(?,?)",Statement.RETURN_GENERATED_KEYS);
		ps.setString(1, taskuid);
		ps.setString(2, foldername);
		ps.executeUpdate();
		ResultSet generatedKeys = ps.getGeneratedKeys();
		
        if (generatedKeys.next()) {
            id=generatedKeys.getLong(1);
        }
		
        //added by rams on 5-june-2012
		generatedKeys.close();
		ps.close();
		
		return id; 
	}
	
	
	/**
	 * Check whether folder is exist
	 * @param taskuid taskuid
	 * @param foldername folder name
	 * @throws Exception
	 */
	private void checkFolderExisting(String taskuid, String foldername) throws Exception {
		PreparedStatement ps3=this.connection().prepareStatement("select folder_name from scheduler_folder where  taskuid=? AND folder_name=? ");
		ps3.setString(1, taskuid);
		ps3.setString(2, foldername);
		ResultSet rs3=ps3.executeQuery();
		if(rs3.next()){
			rs3.close();
			throw new Exception("Folder name already existing!");	
		}
		rs3.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void deleteScheduler(int scheduler_id) throws Exception {
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler SET deleted=1, deletedon=? WHERE id=?");
		ps.setTimestamp(1, new Timestamp(new Date().getTime()));
		ps.setInt(2, scheduler_id);
		ps.executeUpdate();
		ps.close();
	}
	

	/**
	 * {@inheritDoc}
	 */	
	public void putBackScheduler(int scheduler_id) throws Exception {
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler SET deleted=NULL, deletedon=NULL WHERE id=?");		
		ps.setInt(1, scheduler_id);
		ps.executeUpdate();
		ps.close();
	}
	

	/**
	 * {@inheritDoc}
	 */	
	public void purgeScheduler(int scheduler_id) throws Exception {
		
		PreparedStatement ps1=this.connection().prepareStatement("delete  from scheduler_taskdata WHERE scheduler_id=?");
		ps1.setInt(1, scheduler_id);
		ps1.executeUpdate();
		ps1.close();
		
		PreparedStatement ps2=this.connection().prepareStatement("delete  from scheduler_logs WHERE scheduler_id=?");
		ps2.setInt(1, scheduler_id);	
		ps2.executeUpdate();
		ps2.close();
		
		PreparedStatement ps3=this.connection().prepareStatement("delete  from scheduler_queuelogs WHERE scheduler_id=?");
		ps3.setInt(1, scheduler_id);	
		ps3.executeUpdate();
        ps3.close();
		
		PreparedStatement ps4=this.connection().prepareStatement("delete   from scheduler_tags WHERE scheduler_id=?");				
		ps4.setInt(1, scheduler_id);
		ps4.executeUpdate();
        ps4.close();
		
		PreparedStatement ps=this.connection().prepareStatement("delete   from scheduler WHERE id=?");				
		ps.setInt(1, scheduler_id);
		ps.executeUpdate();
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Map getScheduler(int scheduler_id) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("Select a.*,b.folder_name,c.tagname as owner_tag,( ");
		sb.append("  select CONCAT(GROUP_CONCAT(cast(tags.tagname as CHAR(8000)) order by tags.tagname SEPARATOR ', '), ', ') "); 
		sb.append("  from scheduler_tags as st ");  
		sb.append("  left outer join tags on tags.id=st.tag_id ");   
		sb.append("  where st.scheduler_id=a.id "); 
		sb.append(") as stags "); 
		sb.append("FROM scheduler as a "); 
		sb.append("LEFT OUTER JOIN scheduler_folder as b on a.folder_id=b.id left outer join tags as c on c.id=a.owner_tag_id "); 
		sb.append("WHERE a.id=? ");
		
		PreparedStatement ps=this.connection().prepareStatement(sb.toString(), ResultSet.CONCUR_READ_ONLY);
		
		ps.setInt(1, scheduler_id);
		ResultSet rs=ps.executeQuery();
		 
		Map data=null;
		if(rs.next()){			
			//data=new BasicRowProcessor().toMap(rs);
			data = GeneralUtilDB.resultsetToMap(rs);
		}
		if(data!=null){
			
			PreparedStatement ps1=this.connection().prepareStatement("Select * from scheduler_taskdata WHERE scheduler_id=?",ResultSet.CONCUR_READ_ONLY);
			
			ps1.setInt(1, scheduler_id);
			ResultSet rs1=ps1.executeQuery();
			while(rs1.next()){
				String shortname=rs1.getString("field_shortname");				
				String val=rs1.getString("val");
				 
				data.put(shortname, val);
			}
			//added by rams on 5-june-2012
			rs1.close();
			ps1.close();
			
		}
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return data;
	}
	
	 
	/**
	 * {@inheritDoc}
	 */	
	public int addSchedulerLog(int scheduler_id, Date start, Date end,String timezone, String status,String messages) throws Exception{
 
		PreparedStatement pstmt=this.connection().prepareStatement("INSERT INTO scheduler_logs(scheduler_id,start_time,end_time,timezone,status,messages) VALUES(?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
		pstmt.setInt(1, scheduler_id);
		pstmt.setTimestamp(2,new Timestamp(start.getTime()));
		pstmt.setTimestamp(3, new Timestamp(end.getTime()));
		pstmt.setString(4, timezone);
		pstmt.setString(5,status);
		pstmt.setString(6,messages);
		pstmt.executeUpdate();
		ResultSet rs1 = pstmt.getGeneratedKeys(); 
		int thisid=0;
		if(rs1.next()){
			thisid=rs1.getInt(1);				
		}
		pstmt.close();
		return thisid;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updateSchedulerLogMsg(int log_id,String messages) throws Exception{
		PreparedStatement pstmt=this.connection().prepareStatement("Update scheduler_logs SET messages=? WHERE id=?");
		pstmt.setString(1, messages);
		pstmt.setInt(2, log_id);		
		pstmt.executeUpdate();		
		pstmt.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	 public Map getQueueLog(int scheduler_id, long trigger_time) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("select * from scheduler_queuelogs WHERE scheduler_id=? AND trigger_time=?; ");
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);		
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		ps.setInt(1, scheduler_id);
		ps.setLong(2, trigger_time);
		ResultSet rs=ps.executeQuery();
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		Map rtn=null;
		if(rs.next()){			
			//rtn=new BasicRowProcessor().toMap(rs);
			rtn = GeneralUtilDB.resultsetToMap(rs);
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();

		return rtn;
	}
	
	
		/**
		 * {@inheritDoc}
		 */	
	public synchronized List listOfQueueLogs(String sids_trids, long now) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		
/*
		if(sids_trids==null){			
			sb.append("select a.*,cast(c.val as char(200)) as dependencies,b.name,b.calling_another_script,b.taskuid,b.timezone,LENGTH(d.console_message) AS console_message_size from ( ");
			sb.append("  select * from scheduler_queuelogs "); 
			sb.append("  WHERE ID in ( select id from ( ");
			sb.append("    select id from scheduler_queuelogs "); 
			sb.append("    where trigger_time<="+now); 
			sb.append("    order by trigger_time desc limit 0 ) temp_table ");
			sb.append("  )	union all ");
			sb.append("  select * from scheduler_queuelogs "); 
			sb.append("  where status is null and trigger_time>"+now); 
			sb.append(")  as a ");
			sb.append("left outer join scheduler as  b on a.scheduler_id=b.id ");   
			sb.append("left outer join scheduler_taskdata as c  on c.scheduler_id=b.id and c.field_shortname ='dependentids' "); 
			sb.append("left outer join scheduler_queuelogs_cmessage as d  on d.scheduler_id =a.scheduler_id and d.trigger_time = a.trigger_time "); 
			sb.append("ORDER BY a.trigger_time asc,a.start_time,a.scheduler_id; ");
		}else{
			sb.append("select a.*,cast(c.val as char(200)) as dependencies,b.name,b.calling_another_script,b.taskuid,b.timezone,LENGTH(d.console_message) AS console_message_size from ( ");
			sb.append("  select * from scheduler_queuelogs "); 
			sb.append("  WHERE ID in ( ");
			sb.append("    select id from scheduler_queuelogs "); 
			sb.append("    where concat(scheduler_id, concat('_',trigger_time) ) IN ("+sids_trids+") and is_triggered<>1 "); 
			sb.append("    AND status IS NULL  ");
			sb.append("  )	union  all ");	
			sb.append("  select * from scheduler_queuelogs "); 
			sb.append("  where status is null and trigger_time>="+now);
			sb.append(")  as a ");	
			sb.append("left outer join scheduler as  b  on a.scheduler_id=b.id "); 
			sb.append("left outer join scheduler_taskdata as c  on c.scheduler_id=b.id and c.field_shortname ='dependentids' "); 
			sb.append("left outer join scheduler_queuelogs_cmessage as d on d.scheduler_id =a.scheduler_id and d.trigger_time = a.trigger_time "); 
			sb.append("ORDER BY a.trigger_time asc,a.start_time,a.scheduler_id; ");
		}		
 */
		
		if(sids_trids==null){		
			sb.append("select a.host, a.scheduler_id, a.trigger_time, a.status, a.db_insert, a.db_update, a.db_delete, a.is_triggered, a.start_time, a.end_time, a.db_connection_ids, a.response_code, ");
			sb.append("cast(c.val as char(200)) as dependencies,b.name,b.calling_another_script,b.taskuid,b.timezone,LENGTH(d.console_message) AS console_message_size from ( ");
			sb.append("  select host, scheduler_id, trigger_time, status, db_insert, db_update, db_delete, is_triggered, start_time, end_time, db_connection_ids, response_code "); 
			sb.append("  from scheduler_queuelogs ");			
			sb.append("  WHERE ID in ( select id from ( ");
			sb.append("    select id from scheduler_queuelogs "); 
			sb.append("    where trigger_time<="+now); 
			sb.append("    order by trigger_time desc limit 0 ) temp_table ");
			sb.append("  )	union all ");
			sb.append("  select host, scheduler_id, trigger_time, status, db_insert, db_update, db_delete, is_triggered, start_time, end_time, db_connection_ids, response_code "); 
			sb.append("  from scheduler_queuelogs ");			
			sb.append("  where status is null and trigger_time>"+now); 
			sb.append(")  as a ");
			sb.append("left outer join scheduler as  b on a.scheduler_id=b.id ");   
			sb.append("left outer join scheduler_taskdata as c  on c.scheduler_id=b.id and c.field_shortname ='dependentids' "); 
			sb.append("left outer join scheduler_queuelogs_cmessage as d  on d.scheduler_id =a.scheduler_id and d.trigger_time = a.trigger_time "); 
			sb.append("ORDER BY a.trigger_time asc,a.start_time,a.scheduler_id; ");
		}else{
			sb.append("select a.host, a.scheduler_id, a.trigger_time, a.status, a.db_insert, a.db_update, a.db_delete, a.is_triggered, a.start_time, a.end_time, a.db_connection_ids, a.response_code, ");
			sb.append("cast(c.val as char(200)) as dependencies,b.name,b.calling_another_script,b.taskuid,b.timezone,LENGTH(d.console_message) AS console_message_size from ( ");
			sb.append("  select host, scheduler_id, trigger_time, status, db_insert, db_update, db_delete, is_triggered, start_time, end_time, db_connection_ids, response_code ");
			sb.append("  from scheduler_queuelogs "); 
			sb.append("  WHERE ID in ( ");
			sb.append("    select id from scheduler_queuelogs "); 
			sb.append("    where concat(scheduler_id, concat('_',trigger_time) ) IN ("+sids_trids+") and is_triggered<>1 "); 
			sb.append("    AND status IS NULL  ");
			sb.append("  )	union  all ");	
			sb.append("  select host, scheduler_id, trigger_time, status, db_insert, db_update, db_delete, is_triggered, start_time, end_time, db_connection_ids, response_code ");
			sb.append("  from scheduler_queuelogs "); 
			sb.append("  where status is null and trigger_time>="+now);
			sb.append(")  as a ");	
			sb.append("left outer join scheduler as  b  on a.scheduler_id=b.id "); 
			sb.append("left outer join scheduler_taskdata as c  on c.scheduler_id=b.id and c.field_shortname ='dependentids' "); 
			sb.append("left outer join scheduler_queuelogs_cmessage as d on d.scheduler_id =a.scheduler_id and d.trigger_time = a.trigger_time "); 
			sb.append("ORDER BY a.trigger_time asc,a.start_time,a.scheduler_id; ");
		}
		
		//System.out.println("query - listOfQueueLogs :"+sb.toString());
		
		log.debug("query:"+sb.toString());
		boolean ro=isReadOnly();
		setReadOnly(true);
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);	
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		//long startTime = System.nanoTime();
		ResultSet rs=ps.executeQuery();
		//long endTime = System.nanoTime();
		//System.out.println("Took - listOfQueueLogs : " + ((endTime - startTime) / 1000000) + "ms");
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		Vector rtn=new Vector();
		while(rs.next()){
			//Map row=new BasicRowProcessor().toMap(rs);
			Map row = GeneralUtilDB.resultsetToMap(rs);
			row.remove("inject_code"); //to avoid too much of text being transported to client.
			row.remove("executed_code"); //to avoid too much of text being transported to client.
			rtn.add(row);			
		}
		//added by rams on 5-june-2012
		setReadOnly(ro); //setting back the original.
		rs.close();
		ps.close();
		return rtn;
	}	
	

	/**
	 * {@inheritDoc}
	 */	
	public synchronized Map listOfQueueLog(int scheduler_id, long trigger_time ) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("select a.*,b.name,b.taskuid,b.timezone from scheduler_queuelogs  as a ");
		sb.append("left outer join scheduler as  b on a.scheduler_id=b.id ");
		sb.append("WHERE a.scheduler_id=? and trigger_time=? ");
		sb.append("ORDER BY a.trigger_time asc,a.start_time,a.scheduler_id; ");
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);	
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ps.setInt(1, scheduler_id);
		ps.setLong(2, trigger_time);
		
		//System.out.println("query - listOfQueueLog :"+sb.toString());
		
		//long startTime = System.nanoTime();
		ResultSet rs=ps.executeQuery();
		//long endTime = System.nanoTime();
		//System.out.println("Took - listOfQueueLog : " + ((endTime - startTime) / 1000000) + "ms");		
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		Map rtn=null;
		if(rs.next()){			
			//rtn=new BasicRowProcessor().toMap(rs);
			rtn = GeneralUtilDB.resultsetToMap(rs);
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();

		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public synchronized List listOfLast15Logs(long now, int scheduler_id) throws Exception {
		//String query="select a.*,b.*,c.id as error_logid,a.id as qlog_id from scheduler_queuelogs as a left outer join scheduler as  b on a.scheduler_id=b.id left outer join scheduler_logs as c on a.log_id=c.id AND c.messages is not null where a.trigger_time<"+now+" AND "+datequery+"  AND  a.host='"+getHostName()+"' order by a.trigger_time desc,a.start_time desc,a.scheduler_id";
		
		StringBuffer sb = new StringBuffer();
		sb.append("select a.*,LENGTH(inject_code) as executed_code_length,LENGTH(inject_code) as inject_code_length,b.*,c.id as error_logid,a.id as qlog_id "); 
		sb.append("from scheduler_queuelogs as a ");
		sb.append("left join scheduler as b on a.scheduler_id=b.id ");
		sb.append("left join scheduler_logs as c on a.log_id=c.id AND c.messages is not null ");
		sb.append("where a.trigger_time<"+now+" AND a.scheduler_id="+scheduler_id+" " ); 
		//sb.append("where a.trigger_time < NOW() AND a.scheduler_id="+scheduler_id );
		sb.append("order by a.trigger_time desc,a.start_time desc limit 50; ");
		
		//System.out.println("SchedulerDB.listOfHistoryQueueLogs()query:"+query);
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);	
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		ResultSet rs=ps.executeQuery();
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		Vector rtn=new Vector();
		while(rs.next()){			
			//Map row=new BasicRowProcessor().toMap(rs);
			Map row = GeneralUtilDB.resultsetToMap(rs);
			row.remove("inject_code"); //to avoid too much of text being transported to client.
			row.remove("executed_code"); //to avoid too much of text being transported to client.			 
			rtn.add(row);
			//rtn.add(new BasicRowProcessor().toMap(rs));
		}
		log.debug("listOfHistoryQueueLogs() called:");		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public String getConsoleMsg(int scheduler_id, long trigger_time) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("Select console_message from scheduler_queuelogs_cmessage WHERE scheduler_id=? and trigger_time=? "); 
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ps.setInt(1,scheduler_id);
		ps.setLong(2,trigger_time);
		ResultSet rs=ps.executeQuery();
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		String rtn=null;
		if(rs.next()){
			rtn=rs.getString("console_message");
		}
		rs.close();
		ps.close();
		return rtn;
	}
	
	//For 2nd Scheduler
	public String getConsoleMsgFrom2ndScheduler(int scheduler_id) throws Exception { 
		
		StringBuffer sb = new StringBuffer();
		sb.append("Select console_message from scheduler_queuelogs_cmessage WHERE scheduler_id=?"); 
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ps.setInt(1,scheduler_id);
		ResultSet rs=ps.executeQuery();
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		String rtn=null;
		if(rs.next()){
			rtn=rs.getString("console_message");
		}
		rs.close();
		ps.close();
		return rtn;
	}
	//For 2nd Scheduler
	public String checkCompletedSignalFromPeer(int scheduler_id) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("select message from scheduler_exeplanlogs where message like '%Server rcvd completed signal%' and scheduler_id=?"); 
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ps.setInt(1,scheduler_id);
		ResultSet rs=ps.executeQuery();
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		String rtn=null;
		if(rs.next()){
			rtn=rs.getString("message");
		}
		rs.close();
		ps.close();
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public synchronized List listOfHistoryQueueLogs(long now, String datequery) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		
/*
		StringBuffer sb = new StringBuffer();
		sb.append("select a.*,LENGTH(inject_code) as executed_code_length,LENGTH(inject_code) as inject_code_length,b.*, ");
		sb.append("c.id as error_logid,a.id as qlog_id,LENGTH(d.console_message) AS console_message_size "); 
		sb.append("from scheduler_queuelogs as a "); 
		sb.append("left join scheduler as  b on a.scheduler_id=b.id "); 
		sb.append("left join scheduler_logs as c on a.log_id=c.id AND c.messages is not null ");  
		sb.append("left join scheduler_queuelogs_cmessage as d on d.scheduler_id =a.scheduler_id and d.trigger_time = a.trigger_time "); 
		sb.append("where a.trigger_time<"+now+" AND "+datequery+" order by a.trigger_time desc,a.start_time desc,a.scheduler_id; ");		
 */
		
		sb.append("select a.host, a.scheduler_id, a.trigger_time, a.status, a.db_insert, a.db_update, a.db_delete, a.is_triggered, a.start_time, a.end_time, a.db_connection_ids, a.response_code, ");
		sb.append("LENGTH(a.inject_code) as executed_code_length,LENGTH(a.inject_code) as inject_code_length, ");
		sb.append("b.timezone, b.taskuid, b.name, ");
		sb.append("c.id as error_logid,a.id as qlog_id,LENGTH(d.console_message) AS console_message_size ");
		sb.append("from scheduler_queuelogs as a ");
		sb.append("left join scheduler as b on a.scheduler_id=b.id ");
		sb.append("left join scheduler_logs as c on a.log_id=c.id AND c.messages is not null "); 
		sb.append("left join scheduler_queuelogs_cmessage as d on d.scheduler_id =a.scheduler_id and d.trigger_time = a.trigger_time "); 
		sb.append("where a.trigger_time<"+now+" AND "+datequery+" order by a.trigger_time desc,a.start_time desc,a.scheduler_id; ");
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		//System.out.println("query - listOfHistoryQueueLogs :"+sb.toString());
		//long startTime = System.nanoTime();
		ResultSet rs=ps.executeQuery();
		//long endTime = System.nanoTime();
		//System.out.println("Took - listOfHistoryQueueLogs : " + ((endTime - startTime) / 1000000) + "ms");
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		Vector rtn=new Vector();

		while(rs.next()){			
			//Map row=new BasicRowProcessor().toMap(rs);
			Map row = GeneralUtilDB.resultsetToMap(rs);
			
			row.remove("inject_code"); //to avoid too much of text being transported to client.
			row.remove("executed_code"); //to avoid too much of text being transported to client.
			rtn.add(row);
			//rtn.add(new BasicRowProcessor().toMap(rs));
		}
		
		log.debug("listOfHistoryQueueLogs() called:");		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();		
		return rtn;
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public void removeQueueLogs(long currentTime, String tasktypes) throws Exception{		 
		
		// execute only if tasktypes has value
		if (tasktypes != null && !"".equals(tasktypes)) {
			
			//PreparedStatement ps=this.connection().prepareStatement("DELETE from scheduler_queuelogs WHERE trigger_time>? AND host=?");
		StringBuffer sb = new StringBuffer();
		sb.append("delete from scheduler_queuelogs ");
		sb.append("where id in( select * from ( ");
		sb.append("select sq.id from scheduler_queuelogs  as sq ");
		sb.append("left outer join scheduler as s on s.id=sq.scheduler_id "); 
		sb.append("where s.taskuid IN ("+tasktypes+") ");
		sb.append(") table_temp ) AND trigger_time>? ");
				
		//PreparedStatement ps=this.connection().prepareStatement("DELETE from scheduler_queuelogs WHERE trigger_time>? ");
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		
		ps.setLong(1, currentTime);
		//ps.setString(2, getHostName());
		ps.executeUpdate();			
		ps.close();
		}	
	
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void removeQueueLog(long currentTime, int scheduler_id) throws Exception{		 
		PreparedStatement ps=this.connection().prepareStatement("DELETE from scheduler_queuelogs WHERE trigger_time>? AND  scheduler_id=?");
		ps.setLong(1, currentTime);
		ps.setInt(2, scheduler_id);
		ps.executeUpdate();			
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updateQueueLogStatus(int id,String status, String computerName) throws Exception{
		
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler_queuelogs SET status=?,log_insertedby=? where id=?");
		ps.setString(1, status);
		ps.setString(2, computerName);
		ps.setInt(3, id);
		ps.executeUpdate();
		ps.close();
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public void updateQueueLogStatus(int scheduler_id, long trigger_time, String status, String computerName) throws Exception{
		
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler_queuelogs SET status=?,log_insertedby=? WHERE scheduler_id=? AND trigger_time=?");
		ps.setString(1, status);
		ps.setString(2, computerName);
		ps.setInt(3, scheduler_id);
		ps.setLong(4, trigger_time);
		ps.executeUpdate();
		ps.close();
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public void updateQueueNullStatus(int scheduler_id, long trigger_time,String status) throws Exception{
		
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler_queuelogs SET status=? WHERE scheduler_id=? AND trigger_time=? AND  (status is null OR status ='')");
		ps.setString(1, status);
		ps.setInt(2, scheduler_id);
		ps.setLong(3, trigger_time);
		ps.executeUpdate();
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updateResponseCode(int scheduler_id, long trigger_time,int code) throws Exception{
		
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler_queuelogs SET response_code=? WHERE scheduler_id=? AND trigger_time=?");
		ps.setInt(1, code);
		ps.setInt(2, scheduler_id);
		ps.setLong(3, trigger_time);
		ps.executeUpdate();
		ps.close();
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public void updateServerStartEnd(int scheduler_id,long  trigger_time,Date start, Date end) throws Exception{
		
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler_queuelogs SET start_time=?,end_time=?,timebyserver=? WHERE scheduler_id=? AND trigger_time=?");
		ps.setTimestamp(1, new Timestamp(start.getTime()));
		ps.setTimestamp(2, new Timestamp(end.getTime()));
		ps.setInt(3, 1);
		ps.setInt(4, scheduler_id);
		ps.setLong(5, trigger_time);
		ps.executeUpdate();
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updateHostAndStarted(int scheduler_id,long  trigger_time,Date start, String host) throws Exception{
		PreparedStatement ps=this.connection().prepareStatement("UPDATE scheduler_queuelogs SET start_time=?,host=? WHERE scheduler_id=? AND trigger_time=?");
		ps.setTimestamp(1, new Timestamp(start.getTime()));
		ps.setString(2, host);	 
		ps.setInt(3, scheduler_id);
		ps.setLong(4, trigger_time);
		ps.executeUpdate();
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public String getHostName() throws Exception {
		return java.net.InetAddress.getLocalHost().getHostName();	
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updateExecutedCodeQLog(int scheduler_id, long trigger_time, String code ) throws Exception{
		String query="UPDATE scheduler_queuelogs SET executed_code=? WHERE scheduler_id=? and trigger_time=?";
		PreparedStatement ps=this.connection().prepareStatement(query);
		ps.setString(1, code);
		ps.setInt(2,scheduler_id);
		ps.setLong(3, trigger_time);
		ps.executeUpdate();		
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updateQueueLog(Collection data, Vector connection_ids, String computerName) throws Exception{
 
			StringBuffer sb = new StringBuffer();
			sb.append("SELECT  * from scheduler_queuelogs WHERE scheduler_id=? AND trigger_time=? "); 
			
			PreparedStatement ps=this.connection().prepareStatement(sb.toString());
			
			String queryinsert="INSERT INTO scheduler_queuelogs(is_triggered,start_time,end_time,status,log_id,host,log_insertedby,db_insert,db_update,db_delete,inject_code,scheduler_id,trigger_time) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)";
			String queryupdate="UPDATE scheduler_queuelogs SET is_triggered=?,start_time=?,end_time=?,status=?,log_id=?,host=?,log_insertedby=?,db_insert=?,db_update=?,db_delete=?,inject_code=? WHERE scheduler_id=? AND trigger_time=?";
			
			Number scheduler_id1=null;
			Number trigger_time1=null;
			for(Iterator i=data.iterator();i.hasNext();){
				Map record=(Map)i.next();
				Number scheduler_id=(Number)record.get("scheduler_id");
				Number trigger_time=(Number)record.get("trigger_time");
				
				if(trigger_time1==null && trigger_time!=null){
					trigger_time1=trigger_time;
				}
				
				if(scheduler_id1==null && scheduler_id!=null){
					scheduler_id1=scheduler_id;
				}
				
				
				if(scheduler_id!=null &&trigger_time!=null && trigger_time.longValue()>0 &&  scheduler_id.intValue()>0){
					PreparedStatement ps1=null;
					
					ps.setInt(1, scheduler_id.intValue());
					ps.setLong(2, trigger_time.longValue());
					//ps.setString(3, getHostName());
					
					this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);	
					
					ResultSet rs=ps.executeQuery();	
					
					this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);	
					
				
					String status1=(String)record.get("status");
					String oldinj_code=null;
					
					if(rs.next()){
						ps1=this.connection().prepareStatement(queryupdate);
						
						if(rs.getString("status")!=null && (status1==null || (status1!=null && status1.equals("")))){
							status1=rs.getString("status");
						}
						if(rs.getString("inject_code")!=null){
							oldinj_code=rs.getString("inject_code");
						}
						
					}else{
						ps1=this.connection().prepareStatement(queryinsert);
					}
					//release JDBC resources
					rs.close();
					
					int is_triggered1=(record.get("is_triggered")==null?0: ((Number)record.get("is_triggered")).intValue());
					
					Date sd=(Date)record.get("start_time");
					Date ed=(Date)record.get("end_time");
										
					Integer log_id=0;
					try{
						log_id=(Integer)record.get("log_id");
					}catch(Exception e){
						
					}
					
					ps1.setInt(1, is_triggered1);
					if(sd!=null){
						ps1.setTimestamp(2,new Timestamp(sd.getTime()));
					}else{
						ps1.setTimestamp(2,null);
					}
					if(ed!=null){
						ps1.setTimestamp(3, new Timestamp(ed.getTime()));		
					}else{
						ps1.setTimestamp(3, null);
					}
				
					ps1.setString(4,status1);
					if(log_id==null){						
						ps1.setInt(5,0);
					}else{
						ps1.setInt(5,log_id);
					}
					
					String host=(String)record.get("host");
					if(host!=null){
						ps1.setString(6,host);
					}else{
						ps1.setString(6,null);
					}
					
					String comp=computerName;
					if(comp!=null){
						ps1.setString(7,comp);
					}else{
						ps1.setString(7,null);
					}
				
					Integer insert=(Integer)record.get("db_insert");
					if(insert!=null){
						ps1.setInt(8,insert);
					}else{
						ps1.setObject(8,null);
					}
				
					Integer update=(Integer)record.get("db_update");
					if(update!=null){
						ps1.setInt(9,update);
					}else{
						ps1.setObject(9,null);
					}
					
					Integer delete=(Integer)record.get("db_delete");
					if(delete!=null){
						ps1.setInt(10,delete);
					}else{
						ps1.setObject(10,null);
					}
			
					
					String code=(String)record.get("inject_code");
					
					if(code!=null && !code.equals("")){
						ps1.setString(11,code);
					}else{
						ps1.setString(11,oldinj_code);	
					}
			
				 
					ps1.setInt(12,scheduler_id.intValue());
					ps1.setLong(13,trigger_time.longValue());				
					ps1.executeUpdate();
					ps1.close();
					
					String console_message=(String)record.get("console_message");
					
					if(console_message!=null){
						PreparedStatement ps3=this.connection().prepareStatement("select scheduler_id from scheduler_queuelogs_cmessage where scheduler_id=? and trigger_time=? ");
						ps3.setInt(1, scheduler_id.intValue());
						ps3.setLong(2, trigger_time.longValue());
						ResultSet rs3=ps3.executeQuery();
						if(rs3.next()){
							PreparedStatement ps4=this.connection().prepareStatement("DELETE FROM scheduler_queuelogs_cmessage where scheduler_id=? and trigger_time=? ");
							ps4.setInt(1, scheduler_id.intValue());
							ps4.setLong(2, trigger_time.longValue());
							ps4.executeUpdate();
							ps4.close();
						}
						rs3.close();
						ps3.close();
						
						PreparedStatement ps5=this.connection().prepareStatement("INSERT INTO scheduler_queuelogs_cmessage(scheduler_id,trigger_time,console_message) VALUES(?,?,?)");
						ps5.setInt(1, scheduler_id.intValue());
						ps5.setLong(2, trigger_time.longValue());
						ps5.setString(3, console_message);						
						ps5.executeUpdate();
					}
				}			 
			}
			ps.close();
			//if(ps1!=null){
			//	ps1.close();
			//}
			log.debug("scheduelr_id1:"+scheduler_id1+" connection_ids:"+connection_ids+" trigger_time1:"+trigger_time1);
			if(scheduler_id1!=null && scheduler_id1.intValue()>0 && connection_ids!=null && connection_ids.size()>0 && trigger_time1!=null && trigger_time1.longValue() > 0){
				//String query=;
				PreparedStatement ps3=this.connection().prepareStatement("INSERT INTO scheduler_auditlog(scheduler_id,trigger_time,connection_id) VALUES(?,?,?)");
				for(Iterator i=connection_ids.iterator();i.hasNext();){					
					ps3.setInt(1, scheduler_id1.intValue());
					ps3.setLong(2, trigger_time1.longValue());
					ps3.setString(3,(String)i.next());					
					ps3.executeUpdate();
				}
				
			}
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Map getDBLogSummary(String con_ids) throws Exception {
	//public Map getDBLogSummary(int scheduler_id, long trigger_time) throws Exception {

		StringBuffer sb = new StringBuffer();
		sb.append("select ");
		sb.append("  CASE action ");
		sb.append("    WHEN 'I' THEN 'db_insert' ");
		sb.append("    WHEN 'D' THEN 'db_delete' ");
		sb.append("    WHEN 'N' OR 'NU' THEN 'db_update' ");
		sb.append("  END   as action_t ");
		sb.append(",count(*) as count_t ");
		sb.append("from audit_logs.gen_logs ");
		sb.append("where connection_id IN("+con_ids+") ");
		sb.append("and action<>'O' ");
		sb.append("group by action ");
				
		log.debug("~~~getDBLogSummary():query:"+sb.toString());
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		//ps.setInt(1, scheduler_id);
		//ps.setLong(2, trigger_time);
		ResultSet rs1=ps.executeQuery();
		HashMap hm=new HashMap();		
		while(rs1.next()){
			String key=rs1.getString("action_t");
			Integer val=rs1.getInt("count_t");
			if(key!=null  && val!=null) {
				hm.put(key,val);
			}
		}
		//added by rams on 5-june-2012
		rs1.close();
		ps.close();
		
		return hm;
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getDataLogHistory(int scheduler_id, long trigger_time) throws Exception {
	
		StringBuffer sb = new StringBuffer();
		sb.append("select ");
		sb.append("dbase+'_'+tablename+'_'+connection_id as uid, ");
		sb.append("STR_TO_DATE(cdate,'%d-%m-%Y') as cdate1, ");
		sb.append("STR_TO_DATE(trans_date,'%d-%m-%Y %H:%i:%s') as trans_date1, ");
		sb.append("trans_date,tablename,dbase,cdate,contract,val,sval, ");
		sb.append("case action ");
		sb.append("when 'O' then 'N1' "); 
		sb.append("else action ");
		sb.append("end as action_t "); 
		sb.append("from audit_logs.gen_logs ");  
		sb.append("where connection_id IN (select connection_id from bbsync.scheduler_auditlog where scheduler_id=? and trigger_time=?) "); 				
		sb.append("order by connection_id,dbase,tablename,trans_date,action_t DESC,contract,cdate,val,sval ");
		
		PreparedStatement ps1=this.connection().prepareStatement(sb.toString());
		ps1.setInt(1, scheduler_id);
		ps1.setLong(2, trigger_time);
		
		Vector rtn=new Vector();
		ResultSet rs1=ps1.executeQuery();
		while(rs1.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs1));
			rtn.add(GeneralUtilDB.resultsetToMap(rs1));
		}
		
		//added by rams on 5-june-2012
		rs1.close();
		ps1.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public String getLogMessages(int log_id) throws Exception {
		PreparedStatement ps1=this.connection().prepareStatement("Select messages from scheduler_logs WHERE id=?");
		
		ps1.setInt(1, log_id);
		
		String rtn=null;
		ResultSet rs1=ps1.executeQuery();
		while(rs1.next()){			
			rtn=rs1.getString("messages");
		}
		
		//added by rams on 5-june-2012
		rs1.close();
		ps1.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public int toggleActive(int scheduler_id) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("update scheduler set active=CASE active WHEN -1 THEN 0 ELSE -1 END where id=?");	
		ps.setInt(1, scheduler_id);
		ps.executeUpdate();
		ps.close();
		
		PreparedStatement ps1=this.connection().prepareStatement("Select active from scheduler WHERE id=?");		
		ps1.setInt(1, scheduler_id);
		ResultSet rs=ps1.executeQuery();
		 
		Map data=null;
		int rtn=0;
		if(rs.next()){			
			rtn=rs.getInt("active");
		}
		rs.close();
		ps1.close();
		return rtn;
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public Integer addOrUpdateSchedulerGetId(int scheduler_id,Map<String,String> data, String taskUID) throws Exception{
		
		Integer thisid=null;
		
		PreparedStatement pstmt;
		boolean updatemode=false;
		if(scheduler_id>0){
				updatemode=true;
				pstmt=this.connection().prepareStatement("UPDATE scheduler SET name=?,exp_second=?,exp_minute=?,exp_hour=?,exp_day=?,exp_week=?,exp_month=?,timezone=?,taskuid=?,folder_id=?,calling_another_script=?,owner_tag_id=? WHERE id=?");	
		}else{
				pstmt=this.connection().prepareStatement("INSERT INTO scheduler(name,exp_second,exp_minute,exp_hour,exp_day,exp_week,exp_month,timezone,taskuid,folder_id,calling_another_script,owner_tag_id,alert_type) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
				//pstmt=this.connection().prepareStatement("INSERT INTO scheduler(name,exp_second,exp_minute,exp_hour,exp_day,exp_week,exp_month,timezone,taskuid,folder_id,calling_another_script,owner_tag_id,alert_type,is_wiki_done,active) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",Statement.RETURN_GENERATED_KEYS);
		}
		 
		pstmt.setString(1, data.get("name"));
		pstmt.setString(2, data.get("exp_second"));
		pstmt.setString(3, data.get("exp_minute"));
		pstmt.setString(4, data.get("exp_hour"));
		pstmt.setString(5, data.get("exp_day"));
		pstmt.setString(6, data.get("exp_week"));
		pstmt.setString(7, data.get("exp_month"));
		pstmt.setString(8, data.get("timezone"));
		pstmt.setString(9, taskUID);
		
		Integer itgr=0;
		try{	itgr=Integer.parseInt((String)data.get("folder_id"));	}catch(Exception e){}		
		pstmt.setInt(10, itgr);
		
		int calling=0;
		try{calling=Integer.parseInt(data.get("calling_another_script"));}catch(Exception e){}		
		pstmt.setInt(11,calling); 
		
		if(data.get("owner_tag_id")!=null){
			try{
				pstmt.setInt(12,Integer.parseInt(data.get("owner_tag_id")));
			}catch(Exception e){
				pstmt.setInt(12,0);
			}
		}else{
			pstmt.setInt(12,0);
		}
		
		//pstmt.setInt(14, Integer.parseInt(data.get("is_wiki_done")));
		//pstmt.setInt(15, Integer.parseInt(data.get("active")));
		
		if(updatemode){
			pstmt.setInt(13, scheduler_id);
			pstmt.executeUpdate();
			
			PreparedStatement pstmt1=this.connection().prepareStatement("DELETE FROM scheduler_taskdata WHERE scheduler_id=?");
			pstmt1.setInt(1, scheduler_id);
			pstmt1.executeUpdate();
			pstmt1.close();
			thisid=scheduler_id;
		}else{
			pstmt.setString(13, "email"); //by default email for new tasks.
			pstmt.executeUpdate();
		}
		
		
	
		
		
		if(!updatemode){
			ResultSet rs1 = pstmt.getGeneratedKeys(); 
			if(rs1.next()){
				thisid=rs1.getInt(1);				
			}
		}
		return thisid;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void addOrUpdateSchedulerInsertTaskdata(Integer thisid,Map<String,String> data, String shortname) throws Exception{	
		PreparedStatement pstmt1=this.connection().prepareStatement("INSERT INTO scheduler_taskdata(field_shortname,val,scheduler_id) VALUES(?,?,?)");
		pstmt1.setString(1,shortname );
		pstmt1.setString(2,data.get(shortname) );
		pstmt1.setInt(3,thisid );
		pstmt1.executeUpdate();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public boolean updateAlertType(String alert_type,int scheduler_id) throws Exception {
		
		Vector peers=new Vector();		
		String query1="UPDATE scheduler SET alert_type=? WHERE id=?";
		PreparedStatement ps1=this.connection().prepareStatement(query1);
		ps1.setString(1, alert_type);		
		ps1.setInt(2, scheduler_id);
		ps1.executeUpdate();
		ps1.close();
		
		return true;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public  List listDependencyList(String ids, Date d) throws Exception {
		//String query="select a.*,b.*,c.id as error_logid,a.id as qlog_id from scheduler_queuelogs as a left outer join scheduler as  b on a.scheduler_id=b.id left outer join scheduler_logs as c on a.log_id=c.id AND c.messages is not null where a.trigger_time<"+now+" AND "+datequery+"  AND  a.host='"+getHostName()+"' order by a.trigger_time desc,a.start_time desc,a.scheduler_id";
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String query="select * from scheduler_queuelogs WHERE scheduler_id IN("+ids+") AND end_time>='"+sdf.format(d)+"' AND is_triggered=1 AND (status='success' OR status='warning') ";
		
		//System.out.println("SchedulerDB.listOfHistoryQueueLogs()query:"+query);
		PreparedStatement ps=this.connection().prepareStatement(query);
		//ps.setDate(1, new java.sql.Date(d.getTime()));
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();

		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getPeersList() throws Exception {		
		
		String query="select peername from peerslist";
		PreparedStatement ps=this.connection().prepareStatement(query);
		ResultSet rs=ps.executeQuery();
		Vector peers=new Vector();
		while(rs.next()){
			String pn=rs.getString("peername");
			peers.add(pn);
		}
		rs.close();
		ps.close();
		
		return peers;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public List getSingleColData(String query) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement(query);
		ResultSet rs=ps.executeQuery();
		ArrayList data=new ArrayList();
		while(rs.next()){
			data.add(rs.getString(1));
		}
		rs.close();
		ps.close();
		return data;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getPeersData() throws Exception  {
		
		String query="select * from peerslist ORDER BY last_online DESC";
		//String query="select * from peerslist_1 ORDER BY last_online DESC";
		PreparedStatement ps=this.connection().prepareStatement(query);
		ResultSet rs=ps.executeQuery();
		Vector data=new Vector();
		while(rs.next()){
			//data.add(new BasicRowProcessor().toMap(rs));
			data.add(GeneralUtilDB.resultsetToMap(rs));
		}
		rs.close();
		ps.close();		
		return data;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public String getPeerFriendlyName(String peername) throws Exception  {
		
		String query="select friendlyname from peerslist WHERE peername=?";
		//String query="select * from peerslist_1 ORDER BY last_online DESC";
		PreparedStatement ps=this.connection().prepareStatement(query);
		ps.setString(1, peername);
		ResultSet rs=ps.executeQuery();		
		String rtn=null;
		if(rs.next()){			
			//data.add(new BasicRowProcessor().toMap(rs));
			rtn=rs.getString("friendlyname");
		}
		rs.close();
		ps.close();		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public  void updatePeersLastOnline(String peername,long time) throws Exception {
		Vector peers=new Vector();		
		String query1="UPDATE peerslist set last_online=? WHERE peername=?";
		PreparedStatement ps1=this.connection().prepareStatement(query1);
		ps1.setLong(1, time);		
		ps1.setString(2, peername);
		ps1.executeUpdate();
		ps1.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void updatePeersNotes(String peername,String notes, String friendlyname,String cmail) throws Exception {
		
		Vector peers=new Vector();		
		String query1="UPDATE peerslist set notes=?, friendlyname=?,contact_mail=? WHERE peername=?";
		PreparedStatement ps1=this.connection().prepareStatement(query1);
		ps1.setString(1, notes);
		ps1.setString(2, friendlyname);
		ps1.setString(3, cmail);
		ps1.setString(4, peername);
		ps1.executeUpdate();
		ps1.close();
		
			//System.out.println("++++++++++++++++++++++++++++++++++++++++++updatePeersList() called");
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public  void updatePeersToggle(String peername,int active, String user) throws Exception {
		Vector peers=new Vector();		
		
		String query1="UPDATE peerslist set active=? WHERE peername=?";
		PreparedStatement ps1=this.connection().prepareStatement(query1);
		ps1.setInt(1, active);		
		ps1.setString(2, peername);
		ps1.executeUpdate();
		ps1.close();
		
		int action=PEER_ASSOCIATION_HISTORY_PEER_ACTIVE;
		if(active==-1){
			action=PEER_ASSOCIATION_HISTORY_PEER_NOACTIVE;
		}
		String taskuid=null;
		trackPeerAssoHistory(taskuid,peername,action, user);		
	}
	

	/**
	 * {@inheritDoc}
	 */	
	public void updatePeersList(String peername) throws Exception {
		
		Vector peers=new Vector();
		String query="select peername from peerslist where peername=?";		
		PreparedStatement ps=this.connection().prepareStatement(query);
		ps.setString(1,peername);
		ResultSet rs=ps.executeQuery();		
		if(!rs.next()){
			String query1="Insert into peerslist(peername) values(?)";
			PreparedStatement ps1=this.connection().prepareStatement(query1);
			ps1.setString(1, peername);
			ps1.executeUpdate();
			ps1.close();
		}
		rs.close();
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getAssociatedPeers(String taskuid) throws Exception {
		
		PreparedStatement ps=null;
		
		ps=this.connection().prepareStatement("Select peername FROM scheduler_taskpeers where taskuid=?");
		ps.setString(1, taskuid);
		
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			rtn.add(rs.getString("peername"));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public  Vector getAssoAvailablePeers(String taskuid) throws Exception {
		PreparedStatement ps=null;
		
		ps=this.connection().prepareStatement("Select peername FROM scheduler_taskpeers where taskuid=? AND peername not IN (select peername from peerslist where active=-1) ");
		ps.setString(1, taskuid);
		
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			rtn.add(rs.getString("peername"));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}


	/**
	 * {@inheritDoc}
	 */	
	public List getLast50PeerActHistory(String peername) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("select a.username,a.taskuid,a.peername,a.action,a.action_datetime ,b.name,c.friendlyname "); 
		sb.append("from scheduler_peers_actionhistory as a ");
		sb.append("left join scheduler_group as b on a.taskuid=b.taskuid "); 
		sb.append("left join peerslist as c on a.peername = c.peername "); 
		sb.append("where a.peername=? ");
		sb.append("order by action_datetime desc limit 50 ");
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		ps.setString(1, peername);
		ResultSet rs=ps.executeQuery();
		ArrayList rtn=new ArrayList();
		while(rs.next()){
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		rs.close();
		ps.close();
		return rtn;		
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public List getLast50TaskActHistory(String taskuid) throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("select a.username,a.taskuid,a.peername,a.action,a.action_datetime ,b.name,c.friendlyname "); 
		sb.append("from scheduler_peers_actionhistory as a "); 
		sb.append("left join scheduler_group as b on a.taskuid=b.taskuid "); 
		sb.append("left join peerslist as c on a.peername = c.peername "); 
		sb.append("where a.taskuid=? "); 
		sb.append("order by action_datetime desc limit 50 "); 
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		ps.setString(1, taskuid);
		ResultSet rs=ps.executeQuery();
		ArrayList rtn=new ArrayList();
		while(rs.next()){
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		rs.close();
		ps.close();
		return rtn;
	}

	
	/**
	 * Track peer association history
	 * @param taskuid task uid
	 * @param peer peer
	 * @param action action
	 * @param user user
	 * @throws Exception
	 */
	private void trackPeerAssoHistory(String taskuid, String peer, int action, String user) throws Exception {
		
		PreparedStatement ps2=this.connection().prepareStatement("INSERT INTO scheduler_peers_actionhistory(taskuid,peername,action,action_datetime,username) VALUES(?,?,?,?,?)  ");
		ps2.setString(1, taskuid);
		ps2.setString(2, peer);
		ps2.setInt(3,action ) ;// ex ScheduledTask.PEER_ASSOCIATION_HISTORY_ADDED
		ps2.setTimestamp(4, new Timestamp(new Date().getTime()));
		ps2.setString(5, user);
		ps2.executeUpdate();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void addPeerTaskuid(String taskuid, String peer, String user) throws Exception {
				
			PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO scheduler_taskpeers(taskuid, peername) SELECT * FROM (SELECT ?,?) AS table_tmp WHERE NOT EXISTS ( SELECT taskuid, peername FROM scheduler_taskpeers WHERE taskuid = ? and peername = ? ) LIMIT 1 ");
			ps1.setString(1, taskuid);
			ps1.setString(2, peer);
			ps1.setString(3, taskuid);
			ps1.setString(4, peer);
			ps1.executeUpdate();
			ps1.close();			
			trackPeerAssoHistory(taskuid,peer,PEER_ASSOCIATION_HISTORY_ADDED,user);
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void deletePeerTaskuid(String taskuid, String peer, String user) throws Exception {
		
		PreparedStatement ps1=this.connection().prepareStatement("DELETE FROM scheduler_taskpeers WHERE taskuid = ? AND peername=? ");
		ps1.setString(1, taskuid);
		ps1.setString(2, peer);
		ps1.executeUpdate();
		ps1.close();
		trackPeerAssoHistory(taskuid,peer,PEER_ASSOCIATION_HISTORY_REMOVED,user);
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getAllPeerAssociation() throws Exception {
		
		PreparedStatement ps=null;		
		ps=this.connection().prepareStatement("Select * FROM scheduler_taskpeers ");
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public Map getLastSuccessfulQLog(int scheduler_id) throws Exception {
		
		StringBuffer sb = new StringBuffer();
		sb.append("select a.* from ( ");
		sb.append("	select scheduler_id,max(trigger_datetime) as trigger_datetime "); 
		sb.append("	from scheduler_queuelogs ");
		sb.append("	WHERE status='success' AND start_time IS NOT NULL AND  end_time IS NOT NULL AND scheduler_id ="+scheduler_id ); 
		sb.append("	group by scheduler_id ");
		sb.append(") as b ");
		sb.append("left outer join scheduler_queuelogs as a on  a.trigger_datetime=b.trigger_datetime and a.scheduler_id=b.scheduler_id; ");
		
		this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);	
		PreparedStatement st=this.connection().prepareStatement(sb.toString(),ResultSet.CONCUR_READ_ONLY);
		
        ResultSet rs=st.executeQuery();
        this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
		Map rtn=null;
		while(rs.next()){			
			//rtn=new BasicRowProcessor().toMap(rs);
			rtn = GeneralUtilDB.resultsetToMap(rs);
		}
		rs.close();
		st.close();	
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getLastSuccessfulQLogs(Vector scheduler_ids) throws Exception {
		
		String ids=null;
        for(Iterator i=scheduler_ids.iterator();i.hasNext();){
        	Object id=i.next();
        	ids=(ids==null)?id+"":ids+","+id;
        }

        String query="select a.* from (select  scheduler_id,max(trigger_datetime) as trigger_datetime  from scheduler_queuelogs	WHERE status='success' AND start_time IS NOT NULL AND  end_time IS NOT NULL AND scheduler_id in ("+ids+") ";
        query+="group by scheduler_id ) as b left outer join scheduler_queuelogs as a on  a.trigger_datetime=b.trigger_datetime and a.scheduler_id=b.scheduler_id";
		Statement st=this.connection().createStatement();
        ResultSet rs=st.executeQuery(query);
		Vector rtn=new Vector();
		while(rs.next()){			
			//rtn.add(new BasicRowProcessor().toMap(rs));
			rtn.add(GeneralUtilDB.resultsetToMap(rs));
		}
		rs.close();
		st.close();
	
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public int addRScript(String name,String script, int restart) throws Exception {
		PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO r_script(name,script,restart) VALUES(?,?,?)",Statement.RETURN_GENERATED_KEYS);
		ps1.setString(1, name);
		ps1.setString(2, script);
		ps1.setInt(3, restart);
		ps1.executeUpdate();
		ResultSet rs1 = ps1.getGeneratedKeys(); 
		int thisid=0;
		if(rs1.next()){
			thisid=rs1.getInt(1);				
		}
		//added by rams on 5-june-2012
		rs1.close();
		ps1.close();
		
		return thisid;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Map getRScript(int script_id) throws Exception {
		PreparedStatement ps=this.connection().prepareStatement("Select name,script,restart FROM r_script where id=?");
		ps.setInt(1, script_id);
		
		ResultSet rs=ps.executeQuery();
	    Map rtn=null;
		if(rs.next()){			
			//rtn= new BasicRowProcessor().toMap(rs);
			rtn = GeneralUtilDB.resultsetToMap(rs);
		} 
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void addRScriptLog(int script_id,String peer, String status, Date start_time, Date end_time, String message) throws Exception {
		PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO r_script_logs(script_id,peer,status,start_time,end_time,message) VALUES(?,?,?,?,?,?)");
		ps1.setInt(1, script_id);
		ps1.setString(2, peer);
		ps1.setString(3, status);
		ps1.setTimestamp(4,new Timestamp(start_time.getTime()));
		ps1.setTimestamp(5,new Timestamp(end_time.getTime()));
		ps1.setString(6, message);
		ps1.executeUpdate();
		
		ps1.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector rScriptLast5Logs() throws Exception {
		StringBuffer sb = new StringBuffer();
		sb.append("select a.*,b.name from r_script_logs as a left join r_script as b on a.script_id=b.id "); 
		sb.append("where a.script_id in (select id from (select id from r_script order by id desc limit 5) temp_table) order by a.script_id desc ");
		PreparedStatement ps=this.connection().prepareStatement(sb.toString());
				
		ResultSet rs=ps.executeQuery();
	    Vector rtn=new Vector();
		while(rs.next()){			
			//Map record= new BasicRowProcessor().toMap(rs);
			Map record= GeneralUtilDB.resultsetToMap(rs);
			rtn.add(record);
		} 
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	

	/**
	 * {@inheritDoc}
	 */	
	public void setGroupOrder( Vector taskuids) throws Exception {		
		//PreparedStatement ps=null;
		
		//ps=this.connection().prepareStatement("delete FROM scheduler_group");		
		//ps.executeUpdate();
		
		//PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO scheduler_group(taskuid,disp_order) VALUES(?,?)");
		PreparedStatement ps1=this.connection().prepareStatement("UPDATE scheduler_group SET disp_order=? WHERE taskuid=?");
		int count=0;
		for(Iterator<String> i=taskuids.iterator();i.hasNext();){
			ps1.setInt(1, count++);
			ps1.setString(2, i.next());			
			ps1.executeUpdate();
		}
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getGroupOrder( ) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("select taskuid FROM scheduler_group ORDER by disp_order");
		ResultSet rs=ps.executeQuery();
	    Vector rtn=new Vector();
		while(rs.next()){
			rtn.add(rs.getString("taskuid"));
		} 
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getAllGroups( ) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("select * FROM scheduler_group ORDER by disp_order");
		ResultSet rs=ps.executeQuery();
	    Vector rtn=new Vector();
		while(rs.next()){
			//Map record= new BasicRowProcessor().toMap(rs);
			Map record = GeneralUtilDB.resultsetToMap(rs);
			rtn.add(record);
		} 
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getActiveGroups( ) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("select * FROM scheduler_group WHERE active<>-1 ORDER by disp_order ");
		ResultSet rs=ps.executeQuery();
	    Vector rtn=new Vector();
		while(rs.next()){
			//Map record= new BasicRowProcessor().toMap(rs);
			Map record = GeneralUtilDB.resultsetToMap(rs);
			rtn.add(record);
		} 
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getGroups(String enginetype ) throws Exception {
		
		PreparedStatement ps=this.connection().prepareStatement("select * FROM scheduler_group WHERE enginetype=? ORDER by disp_order ");
		ps.setString(1, enginetype);
		ResultSet rs=ps.executeQuery();
	    Vector rtn=new Vector();
		while(rs.next()){
			//Map record= new BasicRowProcessor().toMap(rs);
			Map record = GeneralUtilDB.resultsetToMap(rs);
			rtn.add(record);
		} 
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void addSchedulerExeLogs(int scheduler_id, long trigger_time, Date date,String messages,int repCode, String computerName) throws Exception{
 
		PreparedStatement pstmt=this.connection().prepareStatement("INSERT INTO scheduler_exeplanlogs(scheduler_id,trigger_time,trans_datetime,machine,message,repcode) VALUES(?,?,?,?,?,?)");
		pstmt.setInt(1, scheduler_id);
		pstmt.setLong(2,trigger_time);
		pstmt.setTimestamp(3, new Timestamp(date.getTime()));
		pstmt.setString(4, computerName);
		pstmt.setString(5,messages);
		pstmt.setInt(6,repCode);		
		pstmt.executeUpdate();
		 
		pstmt.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public boolean execLogsRepcodeExist(int scheduler_id, long trigger_time, int repcode) throws Exception {
		boolean rtn=false;
		PreparedStatement ps=this.connection().prepareStatement("select * FROM scheduler_exeplanlogs WHERE scheduler_id=? AND trigger_time=? and repcode=?");
		ps.setInt(1, scheduler_id);
		ps.setLong(2, trigger_time);
		ps.setInt(3, repcode);
		ResultSet rs=ps.executeQuery();
	    
		while(rs.next()){
			rtn=true;
		} 
		 
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getSchedulerExeLogs(int scheduler_id, long trigger_time ) throws Exception {
		
		String query = "select trans_datetime, machine, message, repcode FROM scheduler_exeplanlogs WHERE scheduler_id=? AND trigger_time=? ORDER by id";
		
		PreparedStatement ps=this.connection().prepareStatement(query);
		ps.setInt(1, scheduler_id);
		ps.setLong(2, trigger_time);

		//System.out.println("query - getSchedulerExeLogs : "+query);
		//long startTime = System.nanoTime();
		ResultSet rs=ps.executeQuery();
		//long endTime = System.nanoTime();
		//System.out.println("Took - getSchedulerExeLogs : " + ((endTime - startTime) / 1000000) + "ms");
		
	    Vector rtn=new Vector();
		while(rs.next()){
			//Map record= new BasicRowProcessor().toMap(rs);
			Map record= GeneralUtilDB.resultsetToMap(rs);
			Timestamp tsm=(Timestamp)record.get("trans_datetime");
			SimpleDateFormat sdf=new SimpleDateFormat("dd-MMM HH:mm:ss");
			record.put("trans_datetime1", sdf.format(tsm));
			rtn.add(record);
		} 
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getTriggerData(int scheduler_id) throws Exception {
		PreparedStatement ps=this.connection().prepareStatement("select * FROM scheduler_trigger where scheduler_id=?");
		ps.setInt(1,scheduler_id);
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){
			//Map record= new BasicRowProcessor().toMap(rs);
			Map record = GeneralUtilDB.resultsetToMap(rs);
			rtn.add(record);
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public Map getOneRowTriggerData(long row_id) throws Exception {
		PreparedStatement ps=this.connection().prepareStatement("select * FROM scheduler_trigger where id=?");
		ps.setLong(1,row_id);
		ResultSet rs=ps.executeQuery();
		Map record=new HashMap();
		if(rs.next()){
			 //record= new BasicRowProcessor().toMap(rs);
			 record = GeneralUtilDB.resultsetToMap(rs);
			
		}
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return record;
	}
	

	/**
	 * {@inheritDoc}
	 */	
	public void setTriggerData(int scheduler_id, SchedulerTrigger arry[]) throws Exception {
		PreparedStatement ps1=this.connection().prepareStatement("DELETE FROM scheduler_trigger where scheduler_id=?");
		ps1.setInt(1, scheduler_id);
		ps1.executeUpdate();
		ps1.close();		
		PreparedStatement ps=this.connection().prepareStatement("INSERT INTO scheduler_trigger(scheduler_id, exp_second,exp_minute,exp_hour,exp_week,exp_day,exp_month,inject_code) VALUES(?,?,?,?,?,?,?,?)");		
		for(int i=0;i<arry.length;i++){			
			ps.setInt(1,scheduler_id);
			ps.setString(2,arry[i].getExp_second());
			ps.setString(3,arry[i].getExp_minute());
			ps.setString(4,arry[i].getExp_hour());
			ps.setString(5,arry[i].getExp_week());
			ps.setString(6,arry[i].getExp_day());
			ps.setString(7,arry[i].getExp_month());
			ps.setString(8,arry[i].getInject_code());
			ps.executeUpdate();
		}
		ps.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void addPeerThreadStatus(String peername,String queuename, String taskuid, int allowedthread, int scheduler_id) throws Exception {
		PreparedStatement pstmt=this.connection().prepareStatement("INSERT into  peer_queuethreads(peername,queuename,taskuid,allowed_threads,scheduler_id) values(?,?,?,?,?)");
		pstmt.setString(1, peername);
		pstmt.setString(2,queuename);
		pstmt.setString(3, taskuid);
		pstmt.setInt(4, allowedthread);
		pstmt.setInt(5,scheduler_id);		 
		pstmt.executeUpdate();		 
		pstmt.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void removePeerThreadStatus(String peername, int scheduler_id) throws Exception {
		PreparedStatement pstmt=this.connection().prepareStatement("DELETE FROM peer_queuethreads WHERE peername=? AND scheduler_id=?");
		pstmt.setString(1, peername);		
		pstmt.setInt(2,scheduler_id);		 
		pstmt.executeUpdate();		 
		pstmt.close();
	}
	
	
	/**
	 * {@inheritDoc}
	 */	
	public void removeAllPeerThreadStatus(String peername) throws Exception {
		PreparedStatement pstmt=this.connection().prepareStatement("DELETE FROM peer_queuethreads WHERE peername=?");
		pstmt.setString(1, peername);	
		pstmt.executeUpdate();		 
		pstmt.close();		
	}

	
	/**
	 * {@inheritDoc}
	 */	
	public Vector getAvailablePeers(String peers /* "'rhino'" */, String taskuid /* "'peer1','peer2'" */) throws Exception {
		String query="";
		query+="select peername from peerslist ";
		query+="WHERE peername IN ("+peers+") "; 
		query+="AND peername NOT IN ( ";
		query+="  select distinct(peername)  from peer_queuethreads as a ";
		//query+="  where taskuid="+taskuid+" AND peername IN ("+peers+") AND ";
		query+="  where queuename IN (select distinct queuename from  peer_queuethreads WHERE taskuid="+taskuid+") AND peername IN ("+peers+") AND ";
		query+="  a.allowed_threads <= (select count(*) from peer_queuethreads as b where queuename IN (select distinct queuename from  peer_queuethreads WHERE taskuid="+taskuid+") AND b.peername=a.peername) ";
		query+=") ";
		//System.out.println("ScedulerDBSQL: query:"+query);
		PreparedStatement ps=this.connection().prepareStatement(query);
		
		ResultSet rs=ps.executeQuery();
		Vector rtn=new Vector();
		while(rs.next()){			
			rtn.add(rs.getString("peername"));
		}
		
		//added by rams on 5-june-2012
		rs.close();
		ps.close();
		
		return rtn;
	}
	/*
	public int get20RecentMaxDuration(int scheduler_id, long trigger_time) throws Exception {
		
		
		PreparedStatement ps=this.connection().prepareStatement("select max(datediff(millisecond,start_time,end_time)) maxduration_in_last20 from scheduler_queuelogs where id in( select top 20 id from scheduler_queuelogs  where scheduler_id=? and trigger_time<=? and status='success' order by trigger_time desc");
		//PreparedStatement ps=this.connection().prepareStatement("select count(*) as overlapx from  scheduler_queuelogs where id in (select top "+no_oftimes+"  id from scheduler_queuelogs  where scheduler_id=? and trigger_time>? order by trigger_time) and status='overlapped'");
		
		ps.setInt(1, scheduler_id);
		ps.setLong(2, trigger_time);		
		ResultSet rs=ps.executeQuery();		 
		Map data=null;
		int rtn=0;
		if(rs.next()){			
			rtn=rs.getInt("maxduration_in_last20");
		}
		return rtn;
	}
    */
	
	
	/**
	 * {@inheritDoc}
	 */	
	public long getTimeoutCriteriaInMs(int scheduler_id) throws Exception {
		
			String query="select max(cast((UNIX_TIMESTAMP(end_time)*1000 - UNIX_TIMESTAMP(start_time)*1000) as int)) as maxlast_50 from scheduler_queuelogs where id in (select * from (select id from  scheduler_queuelogs where scheduler_id=? and status='success' order by start_time desc limit 50) temp_table)";

			PreparedStatement ps=this.connection().prepareStatement(query);
			ps.setInt(1, scheduler_id);			 		
			ResultSet rs=ps.executeQuery();		 
			 
			long rtn=0;
			if(rs.next()){			
				rtn=rs.getLong(1);
			}
			return rtn;
	 }

	
	/**
	 * {@inheritDoc}
	 */	
	 public long getMaxDurationInLast50Exec(int scheduler_id) throws Exception {
		 
		 boolean err=true;
		 long rtn=0;
		 int count=0;
		 while(err && count<5){
			try{ 
				count++;
				err=false;				
			    
			    StringBuffer sb = new StringBuffer();
			    sb.append("select max(cast((UNIX_TIMESTAMP(end_time)*1000 - UNIX_TIMESTAMP(start_time)*1000) as int))*2 as maxlast_50 ");
			    sb.append("from scheduler_queuelogs "); 
			    sb.append("where id in( "); 
			    sb.append("	select id from ( ");
			    sb.append("	select id from  scheduler_queuelogs ");
			    sb.append("	where scheduler_id=? and status='success' order by start_time desc limit 50 ");
			    sb.append("	) temp_table ");
			    sb.append("); ");
			    
			    this.connection().setTransactionIsolation(Connection.TRANSACTION_READ_UNCOMMITTED);	
			    PreparedStatement ps=this.connection().prepareStatement(sb.toString());
			    
				ps.setInt(1, scheduler_id);				 		
				ResultSet rs=ps.executeQuery();
				this.connection().setTransactionIsolation(Connection.TRANSACTION_REPEATABLE_READ);
				if(rs.next()){			
					rtn=rs.getLong("maxlast_50");
				}
				
			}catch(SQLException ex){
				
				log.error("getMaxDurationInLast50Exec(), Error message e:"+ex.getMessage());
				if(ex.getMessage().contains("was deadlocked on lock resources with another process")){
					log.error("getMaxDurationInLast50Exec(), try "+count);
					err=true;
					Thread.sleep(50);
				}else{
					throw ex;
				}
			}
		 }
			return rtn;
	 }
	
	 /*
	 public Vector getFollowers(int scheduler_id) throws Exception {
			PreparedStatement ps=this.connection().prepareStatement("select username FROM scheduler_followers WHERE scheduler_id=?");
			ps.setInt(1, scheduler_id);
			ResultSet rs=ps.executeQuery();
			Vector v=new Vector();
			while(rs.next()){
				v.add(rs.getString("username"));
			}
			rs.close();
			ps.close();
			return v;
	 }
 
	  public void followFunction(int scheduler_id, String username) throws Exception {		
		 
			PreparedStatement ps1=this.connection().prepareStatement("INSERT scheduler_followers(username, scheduler_id) SELECT ?,? WHERE (select count(*) FROM scheduler_followers WHERE username=? AND scheduler_id=?)=0 ");
			ps1.setString(1,username);
			ps1.setInt(2,scheduler_id);
			ps1.setString(3,username);
			ps1.setInt(4,scheduler_id);	
			ps1.executeUpdate();
			ps1.close();
			 
		}

		public void unFollowFunction(int scheduler_id, String username) throws Exception {	
			 
			PreparedStatement ps1=this.connection().prepareStatement("DELETE FROM scheduler_followers WHERE username=? AND scheduler_id=?");
			ps1.setString(1,username);
			ps1.setInt(2,scheduler_id);		 	
			ps1.executeUpdate();
			ps1.close();
			 
		}
			 
		*/
	 

	 
	/**
	 * {@inheritDoc}
	 */	
	 public String getOwnerTheme(int scheduler_id) throws Exception {
		 
		 String query=" select b.tagname from scheduler as a left outer join tags as b on b.id=a.owner_tag_id where a.id=?";
		 PreparedStatement ps=this.connection().prepareStatement(query);
		 ps.setInt(1, scheduler_id);
		 ResultSet rs=ps.executeQuery();
		 String tagname=null;
		 if(rs.next()){
			 tagname=rs.getString("tagname");
			 tagname=tagname.replaceAll("thm-", "");
		 }
		 
		 return tagname;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public void updateWikiDone(int scheduler_id, int done) throws Exception {
			String query="UPDATE scheduler set is_wiki_done=? where  id=?";
			PreparedStatement ps=this.connection().prepareStatement(query);
			ps.setInt(1, done);
			ps.setInt(2, scheduler_id);
			ps.executeUpdate();
			ps.close();
		}
	 

	/**
	 * {@inheritDoc}
	 */	
	 public void updateLast2UsersTag(int scheduler_id, int user_tagid) throws Exception {
     
	     // works without 'limit 2', the result is equal.
		 String query="DELETE FROM scheduler_tags WHERE id IN ( select id from ( SELECT st.id FROM scheduler_tags as st ";
		 query+=" LEFT OUTER JOIN tags  on tags.id=st.tag_id ";
		 query+=" WHERE st.id NOT IN( ";
		 query+="   select st1.id from scheduler_tags as st1 ";
		 query+="   left outer join tags as t1 on t1.id=st1.tag_id ";
		 query+="   WHERE LEFT(t1.tagname,4)='usr-' AND st1.scheduler_id=st.scheduler_id ";
		 query+="   order by st1.id desc "; 
		 query+=" ) "; 
		 query+=" AND LEFT(tags.tagname,4)='usr-' AND st.scheduler_id=? ) temp_table) ";
	     
	     PreparedStatement ps=this.connection().prepareStatement(query);
		 ps.setInt(1, scheduler_id);
		 ps.executeUpdate();
		 ps.close();
		 
		 PreparedStatement ps2=this.connection().prepareStatement("DELETE FROM scheduler_tags WHERE scheduler_id=? AND tag_id=?");
		 ps2.setInt(1, scheduler_id);
		 ps2.setInt(2, user_tagid);
		 ps2.executeUpdate();
		 
		 PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO scheduler_tags(scheduler_id,tag_id) VALUES(?,?)");
		 ps1.setInt(1, scheduler_id);
		 ps1.setInt(2, user_tagid);
		 ps1.executeUpdate();
		 ps1.close();
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	 
	 public int addIfTagNotExist(String tagname) throws Exception {
		 
		    PreparedStatement ps=this.connection().prepareStatement("select * FROM tags WHERE tagname=?");
		    ps.setString(1, tagname);
		    ResultSet rs=ps.executeQuery();
		    int id=0;
		    if(rs.next()){
		    	id=rs.getInt("id");
		    }else{		 
		    	PreparedStatement ps1=this.connection().prepareStatement("insert into tags(tagname) values(?)",Statement.RETURN_GENERATED_KEYS);
			    ps1.setString(1, tagname);			 
			    ps1.executeUpdate();
			    ResultSet generatedKeys = ps1.getGeneratedKeys();			
			    if (generatedKeys.next()) {
			    	id=generatedKeys.getInt(1);
			    }
		    }
		   return id;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public Map getTaskEventActions(int scheduler_id,long trig_time) throws Exception{
		 
		 String q="select  field_shortname,val from scheduler_taskdata "; 
		        q+=" where field_shortname like 'on%' ";
		        q+=" and scheduler_id=? ";
		        q+=" union all ";
		    	q+=" select 'status' as field_shortname,status as val from scheduler_queuelogs ";
		    	q+=" where scheduler_id=? and trigger_time =? ";
		    	
		    	PreparedStatement ps=this.connection().prepareStatement(q);
				ps.setInt(1, scheduler_id);
				ps.setInt(2, scheduler_id);
				ps.setLong(3, trig_time);				 
				ResultSet rs=ps.executeQuery();
				HashMap al=new HashMap();
				while(rs.next()){
					al.put(rs.getString(1),rs.getString(2));
					
				}
				return al;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public String getErrorMessageEvenNull(int scheduler_id,long trig_time) throws Exception {
		 
		 String q="select b.messages from scheduler_queuelogs as a ";
		 q+="left outer join scheduler_logs as b on a.log_id=b.id ";
		 q+="where a.status='fail' ";
		 q+="and a.scheduler_id=? and a.trigger_time=? ";

		 PreparedStatement ps=this.connection().prepareStatement(q);
		 ps.setInt(1, scheduler_id);
		 ps.setLong(2, trig_time);
		 
		 ResultSet rs=ps.executeQuery();
		 
		 String rtn=null;
		 if(rs.next()){			 
			rtn=rs.getString("messages");
				 
		 }
		 return rtn;
	 }
 
	 
	/*	 
	 public void pushAlarmMessage(String message) throws Exception {
		 PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO tradingRef.stackAlarms(Date,Message,status) VALUES(NOW(),?,0)");
		 ps1.setString(1, message);	     
		 ps1.executeUpdate();
		 ps1.close();
	 }
	 */
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public void pushAlarmMessage(String db_name_trading_ref, String message) throws Exception {
		 PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO " + db_name_trading_ref + ".stackAlarms(Date,Message,status) VALUES(NOW(),?,0)");
		 ps1.setString(1, message);	     
		 ps1.executeUpdate();
		 ps1.close();
	 }	 
	 
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public List<Integer> getDependsThis(int scheduler_id) throws Exception {
		 String query="select scheduler_id from scheduler_taskdata where field_shortname='dependentids' AND (val LIKE '"+scheduler_id+"' OR val LIKE '"+scheduler_id+",%' OR val LIKE '%,"+scheduler_id+",%' OR val LIKE '%,"+scheduler_id+"' )";
		
		 log.debug("query:"+query);
		 PreparedStatement ps=this.connection().prepareStatement(query);
		 ResultSet rs=ps.executeQuery();
		 ArrayList<Integer> ids=new ArrayList();
		 while(rs.next()){
			 int sid=rs.getInt("scheduler_id");
			 ids.add(sid);
		 }
		 return ids;
	 }

	 
	/**
	 * {@inheritDoc}
	 */	
	 public List<Integer> getDependsTo(int scheduler_id) throws Exception {
		 String query="select val from scheduler_taskdata where field_shortname='dependentids' AND scheduler_id = "+scheduler_id;
		
		 log.debug("query:"+query);
		 PreparedStatement ps=this.connection().prepareStatement(query);
		 ResultSet rs=ps.executeQuery();
		 ArrayList<Integer> ids=new ArrayList();
		 while(rs.next()){
			 List<String> vals = Arrays.asList(rs.getString("val").split("\\s*,\\s*"));
			 for (int i=0; i<vals.size(); i++) {
				 ids.add(Integer.valueOf(vals.get(i)));
			 }
		 }
		 return ids;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */			 
	 public void addEditLogs(int scheduler_id,String user, String message) throws Exception {
			PreparedStatement pstmt=this.connection().prepareStatement("INSERT INTO scheduler_editlogs(scheduler_id,username,message,edited_datetime) VALUES(?,?,?,?)");
			pstmt.setInt(1, scheduler_id);
			pstmt.setString(2,user);
			pstmt.setString(3, message);
			pstmt.setTimestamp(4, new Timestamp(new Date().getTime()));					 
			pstmt.executeUpdate();		 
			pstmt.close();
	  }
	
	 
	/**
	 * {@inheritDoc}
	 */	
	 public List getEditLogs(int scheduler_id) throws Exception {
		 
		 ArrayList al=new ArrayList();
		 String query="select * from scheduler_editlogs where scheduler_id=?";			
		 PreparedStatement ps=this.connection().prepareStatement(query);
		 ps.setInt(1, scheduler_id);
		 ResultSet rs=ps.executeQuery();		 
		 while(rs.next()){
			 
			 //al.add(new BasicRowProcessor().toMap(rs));
			 al.add(GeneralUtilDB.resultsetToMap(rs));
		 }
		 rs.close();
		 ps.close();
		 
		 return al;
	  }
	 
	 
	/**
	 * {@inheritDoc}
	 */	 
	 public String getInjectCode4QLog(String sid_triggertime) throws Exception {
		 String query="select inject_code from scheduler_queuelogs where concat(scheduler_id, concat('_',trigger_time) )=?";	
		 PreparedStatement ps=this.connection().prepareStatement(query);
		 ps.setString(1,sid_triggertime);
		 ResultSet rs=ps.executeQuery();
		 String rtn=null;
		 if(rs.next()){
			 rtn=rs.getString("inject_code");
		 }		 
		 return rtn;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public void updateTimeoutSettings(Map data) throws Exception {		  
		 
		 PreparedStatement d_ps=this.connection().prepareStatement("DELETE FROM scheduler_timeout_settings where ky=?");
		 PreparedStatement i_ps=this.connection().prepareStatement("INSERT INTO scheduler_timeout_settings(ky,val) VALUES(?,?)");
		 for(Iterator<String> it=data.keySet().iterator();it.hasNext();){
			 String ky=it.next();
			 String val=(String)data.get(ky);
			 d_ps.setString(1, ky);
			 d_ps.executeUpdate();
			 
			 i_ps.setString(1,ky);
			 i_ps.setString(2, val);
			 i_ps.executeUpdate();
		 }		 
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public Map getTimeoutSettings() throws Exception {
		  
		 HashMap h=new HashMap<String, String>();
		 PreparedStatement d_ps=this.connection().prepareStatement("SELECT * FROM scheduler_timeout_settings");
		 ResultSet rs=d_ps.executeQuery();
		 
		 while(rs.next()){
			 h.put(rs.getString("ky"), rs.getString("val"));
			 
		 }
		 return h;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public ArrayList getLast10minuteSuspectedFailure() throws Exception {
		 
		 ArrayList al=new ArrayList();
		 
		 StringBuffer sb = new StringBuffer();
		 sb.append("select a.trigger_time,a.scheduler_id from scheduler_exeplanlogs as a ");
		 sb.append("left outer join scheduler_queuelogs as b on ( a.scheduler_id = b.scheduler_id and a.trigger_time = b.trigger_time) "); 
		 sb.append("where a.trans_datetime between DATE_ADD(NOW(), interval -20 minute) and DATE_ADD(NOW(), interval -10 minute) "); 
		 sb.append(" and (b.status is null) ");   
		 sb.append(" order by trans_datetime desc "); 
			
		 PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		 
		 ResultSet rs=ps.executeQuery();		 
		 while(rs.next()){			 
			 //al.add(new BasicRowProcessor().toMap(rs));
			 al.add(GeneralUtilDB.resultsetToMap(rs));
		 }
		 rs.close();
		 ps.close();		 
		 return al;
	 }
 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public boolean isAnyExecLogsInLast3Mins(int scheduler_id, long trigger_time) throws Exception {
		 
		 boolean found=false;
		 
		 StringBuffer sb = new StringBuffer();
		 sb.append("select count(*) ct from scheduler_exeplanlogs ");		 
		 sb.append("WHERE trans_datetime > DATE_ADD(NOW(), interval -3 minute) AND scheduler_id=? AND trigger_time=? ");
			
		 PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		 ps.setInt(1, scheduler_id);
		 ps.setLong(2, trigger_time);		 
		 ResultSet rs=ps.executeQuery();		 
		 while(rs.next()){			 
			 found=rs.getInt("ct")>0?true:false; 
		 }
		 return found;
	 }
	 

	/**
	 * {@inheritDoc}
	 */	
	 public ArrayList getPeersList4Engine(List<String> enginetypes) throws Exception {
		 
		 String eng="";	
		    for(String tg:enginetypes){
		    	eng+=(eng.equals(""))?"'"+tg+"'":",'"+tg+"'";
		    }
		    
		 
		 String query="select * from peerslist ";
		 query+=" where peername in( ";
		 query+=" select distinct peername from scheduler_taskpeers "; 
		 query+=" where taskuid in(select taskuid from scheduler_group where enginetype IN ("+eng+")) ";
		 query+=" ) ";		 
		 PreparedStatement ps=this.connection().prepareStatement(query);
		// ps.setString(1, enginetype);
		 ResultSet rs=ps.executeQuery();
		 ArrayList al=new ArrayList();
		 while(rs.next()){
			 //al.add(new BasicRowProcessor().toMap(rs));
			 al.add(GeneralUtilDB.resultsetToMap(rs));
		 }
		 return al;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public void userPrefSaveOrUpdate(String login, String ky, String val) throws Exception {
		 
		 PreparedStatement ps=this.connection().prepareStatement("DELETE FROM user_preference WHERE login=? AND ky=?");
		 ps.setString(1, login);
		 ps.setString(2, ky);
		 ps.executeUpdate();
		 
		 log.debug("after deleting..");
		 if(val!=null){
			 
			 PreparedStatement ps1=this.connection().prepareStatement("INSERT INTO user_preference(login,ky,val) VALUES(?,?,?)");
			 
			 ps1.setString(1, login);
			 ps1.setString(2, ky);
			 ps1.setString(3, val);
			 ps1.executeUpdate();
			 log.debug("after inserting..");
		 }
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public Map userPrefGetAll(String login)  throws Exception {
		 PreparedStatement ps=this.connection().prepareStatement("SELECT ky,val FROM user_preference where login=?");
		 ps.setString(1, login);
		 ResultSet rs=ps.executeQuery();
		 TreeMap rtn=new TreeMap();
		 while(rs.next()){
			 rtn.put(rs.getString("ky"), rs.getString("val").toString());
		 }
		 rs.close();
		 ps.close();
		 return rtn;
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public List getAutoCompleteXHR(String keyword) throws Exception {
		 
		 String theme=null;
		 
		 //System.out.println(" legnth:"+keyword.split(":").length);

		 
		 if(keyword.contains(":") &&  keyword.split(":").length>1){
			 theme=keyword.split(":")[0];
			 keyword=keyword.split(":")[1];
		 }
		 
		 if(keyword.contains(":") &&  keyword.split(":").length==1){
			 theme=keyword.split(":")[0];
			 keyword=null;
			 
		 }
		 
		 StringBuffer sb = new StringBuffer();
		 sb.append("select a.name,a.id,b.folder_name,c.name as group_name,d.edited_datetime,d.username, c.icon, ");
		 sb.append("(select CONCAT(GROUP_CONCAT(cast(tags.tagname as CHAR(8000)) order by tags.tagname SEPARATOR ', '), ', ') from scheduler_tags as st ");  
		 sb.append("left outer join tags on tags.id=st.tag_id "); 
		 sb.append("WHERE st.scheduler_id=a.id "); 
		 sb.append(") as stags "); 
		 sb.append("from scheduler as a "); 
		 sb.append("left outer join scheduler_folder as b on a.folder_id=b.id "); 
		 sb.append("left outer join scheduler_group as c on a.taskuid=c.taskuid "); 
		 sb.append("left outer join scheduler_editlogs as d on d.scheduler_id=a.id AND d.id = ");
		 sb.append("(select dd.id from scheduler_editlogs as dd where dd.scheduler_id= a.id order by dd.edited_datetime DESC limit 1) "); 		 
		 sb.append("where ( (a.deleted is null OR a.deleted<>1) and c.active>=0 ) ");
		 if(keyword!=null){
			 sb.append("and(a.name like '%"+keyword+"%' OR cast(a.id as char(10)) like '%"+keyword+"%' ) ");
		 }
		 if(theme!=null){
			 sb.append("AND a.id in (select scheduler_id from scheduler_tags left outer join tags on scheduler_tags.tag_id = tags.id where tags.tagname='thm-"+theme.trim()+"' )" );
		 }
		 sb.append("ORDER BY d.edited_datetime DESC "); 
		 PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		 ResultSet rs=ps.executeQuery();
		 ArrayList al=new ArrayList();
		 while(rs.next()){
			 //al.add(new BasicRowProcessor().toMap(rs));
			 al.add(GeneralUtilDB.resultsetToMap(rs));
		 }
		 return al;
	 }

	 
	/**
	 * {@inheritDoc}
	 */	
	 public List getFailedLast2Days(List<String> themes) throws Exception {
		 
		 StringBuffer sbThemes = new StringBuffer();
		 for (String t : themes) { 
		     if (sbThemes.length() > 0) sbThemes.append(',');
		     sbThemes.append("'").append(t).append("'");
		 }
		 String themeStr = sbThemes.toString();
		 
		 StringBuffer sb = new StringBuffer();
		 
		 if(false){
			 sb.append("select count(*) as num_failed,scheduler_id,b.name as name,status,max(trigger_time) as last_trigger from  bbsync.scheduler_queuelogs as a ");
			 sb.append("LEFT JOIN bbsync.scheduler as b on a.scheduler_id=b.id WHERE scheduler_id IN ");
			 sb.append("( select scheduler_id FROM bbsync.scheduler_tags WHERE tag_id IN "); 
			 sb.append("  (select id from bbsync.tags WHERE tagname in (" + themeStr + ")) ");
			 sb.append(") AND trigger_datetime>=DATE_ADD(NOW(), INTERVAL -2 DAY) ");
			 sb.append("AND a.status IS NOT NULL AND a.status NOT IN ('success','overlapped','warning','re-executed') ");
			 sb.append("GROUP BY scheduler_id,b.name,status ");
			 sb.append("ORDER BY max(trigger_time) desc ");
			 
		 }else{
			 
			 sb.append("select count(*) as num_failed,scheduler_id,b.name as name,status,max(trigger_time) as last_trigger from  scheduler_queuelogs as a ");
			 sb.append("LEFT JOIN scheduler as b on a.scheduler_id=b.id WHERE scheduler_id IN ");
			 sb.append("( select scheduler_id FROM scheduler_tags WHERE tag_id IN ");
			 sb.append("  (select id from tags WHERE tagname in (" + themeStr + ")) ");
			 sb.append(") AND trigger_datetime>=DATE_ADD(NOW(), INTERVAL -2 DAY) ");
			 sb.append("AND a.status IS NOT NULL AND a.status NOT IN ('success','overlapped','warning','re-executed') ");
			 sb.append("GROUP BY scheduler_id,b.name,status ");
			 sb.append("ORDER BY max(trigger_time) desc ");
			 
		 }
		 PreparedStatement ps=this.connection().prepareStatement(sb.toString());
		 
		 ResultSet rs=ps.executeQuery();
		 ArrayList al=new ArrayList();
		 while(rs.next()){
			 //al.add(new BasicRowProcessor().toMap(rs));
			 al.add(GeneralUtilDB.resultsetToMap(rs));
		 }
		
		 return al;
	 }
 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public String getTop20IdNameByNameQuery(String keyword) throws Exception {
		 return "SELECT concat(concat(cast(id as char(10)),'|'),name) from scheduler where name like '%"+keyword+"%' limit 20";
	 }
 	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public String getTop20IdNameByIdQuery(String keyword) throws Exception {
		 return "SELECT concat(concat(cast(id as char(10)),'|'),name) from scheduler where cast(id as char(10)) like '%"+keyword+"%' limit 20";
	 }
	 
	 
	/**
	 * {@inheritDoc}
	 */	
	 public String getHistoryQueueLogsDateQuery(long scheduelr_id, String stat) {
		 return " a.trigger_datetime>=DATE_ADD(NOW(), interval -2 day) AND a.scheduler_id="+scheduelr_id+" AND a.status='"+stat+"'";
	 }
	 

}