<%@ page import="java.util.*"%>
<%@ page import="com.eactive.eai.common.message.*,java.text.SimpleDateFormat"%>
<%@ page import="javax.jms.*,com.eactive.eai.flowcontrol.jms.*,javax.naming.*"%>
<%@ page language="java" contentType="text/html;charset=utf-8"%>
<%!
public final static String JMS_FACTORY = "com.eactive.eai.common.FlowRouterConnectionFactory";

public ArrayList displayQueue(String queueName, String mSelector, int maxCount) throws Exception {
	
	ArrayList al = new ArrayList();
	
	InitialContext ctx = ctx = new InitialContext();
	
	QueueConnectionFactory qconFactory = null;
	QueueConnection qcon = null;
	QueueSession qsession = null;
	QueueBrowser qbrowser = null;
	javax.jms.Queue queue = null;
	
	int count = 0;
	try {
		java.text.DateFormat DATE_FORMAT = DATE_FORMAT = java.text.DateFormat.getDateTimeInstance(
				java.text.DateFormat.SHORT, java.text.DateFormat.SHORT);
		if (DATE_FORMAT instanceof java.text.SimpleDateFormat)
			((java.text.SimpleDateFormat) DATE_FORMAT)
					.applyPattern("yy/MM/dd kk:mm:ss");
		
		qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
	    qcon = qconFactory.createQueueConnection();
	    
	    qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	    queue = (javax.jms.Queue) ctx.lookup(queueName);
		
		if(mSelector != null && mSelector.length() > 0) {
	    	qbrowser = qsession.createBrowser(queue, mSelector);
	    }
	    else {
			qbrowser = qsession.createBrowser(queue);
		}    	
	    qcon.start();
		
		Enumeration e = qbrowser.getEnumeration();
	    Message m = null;

	    if (! e.hasMoreElements()) {
			System.out.println("There are no messages on this queue. - " + queueName);
		} 
		else {
			System.out.println(queueName + " - Queued JMS Messages: "+DATE_FORMAT.format(new java.util.Date(System
					.currentTimeMillis())));
			
			while (e.hasMoreElements()) {
				m = (Message) e.nextElement();
				count++;
				System.out.println("get Message " + count );
						
				/*
				System.out.println("Message ID " + m.getJMSMessageID() +
				               " delivered " + new Date(m.getJMSTimestamp()) +
				               " to " + m.getJMSDestination());
				System.out.print("\tExpires        ");
	        
				if (m.getJMSExpiration() > 0) {
					System.out.println( new Date( m.getJMSExpiration()));
				}
				else {
					System.out.println("never");
				}
	        
				System.out.println("\tPriority        " + m.getJMSPriority());
				System.out.println("\tMode            " + (
	                      m.getJMSDeliveryMode() == DeliveryMode.PERSISTENT ?
	                                       "PERSISTENT" : "NON_PERSISTENT"));
				System.out.println("\tCorrelation ID  " + m.getJMSCorrelationID());
				System.out.println("\tReply to        " + m.getJMSReplyTo());
				System.out.println("\tMessage type    " + m.getJMSType());
				System.out.println("\tMessage BizCode " + m.getStringProperty("BizCode"));
	        
				if (m instanceof TextMessage) {
					System.out.println("\tTextMessage    \"" +
							((TextMessage)m).getText() + "\"");
				}
				*/
				
				if(count > maxCount) {
					break;
				}
				else {
					if(m instanceof ObjectMessage) {
						al.add(m);
					}
				}
			}
		}
	}
	catch( Exception e ) {
		//e.printStackTrace();
	}
	finally {
		try {
			if(qbrowser != null) qbrowser.close();
			if(qsession != null) qsession.close();
			if(qcon     != null) qcon.close();
		}
		catch(Exception ex) {}
	}
	return al;
}

public ArrayList purgeQueue(String queueName, String mSelector, int purgeSize, boolean isLogging) throws Exception {
	
	ArrayList al = new ArrayList();
	
	InitialContext ctx = new InitialContext();
	
	QueueConnectionFactory qconFactory = null;
	QueueConnection qcon = null;
	QueueSession qsession = null;
	QueueReceiver qreceiver = null;
	javax.jms.Queue queue = null;
	
	long sTime = System.currentTimeMillis();
	
	long cTime = 0;
	
	int purgeCount = 0;
	
	try {
		java.text.DateFormat DATE_FORMAT = DATE_FORMAT = java.text.DateFormat.getDateTimeInstance(
				java.text.DateFormat.SHORT, java.text.DateFormat.SHORT);
		if (DATE_FORMAT instanceof java.text.SimpleDateFormat)
			((java.text.SimpleDateFormat) DATE_FORMAT)
					.applyPattern("yy/MM/dd kk:mm:ss");
		
		qconFactory = (QueueConnectionFactory) ctx.lookup(JMS_FACTORY);
	    qcon = qconFactory.createQueueConnection();
	    
	    qsession = qcon.createQueueSession(false, Session.AUTO_ACKNOWLEDGE);
	    queue = (javax.jms.Queue) ctx.lookup(queueName);
		
		if(mSelector != null && mSelector.length() > 0) {
			qreceiver = qsession.createReceiver(queue, mSelector);
	    }
	    else {
			qreceiver = qsession.createReceiver(queue);
		}    	
	    qcon.start();
		
		Message m = null;

		System.out.println(">> "+queueName + " - Queued JMS Messages: "+DATE_FORMAT.format(new java.util.Date(System
				.currentTimeMillis())));
		cTime = System.currentTimeMillis() - sTime;
		sTime = System.currentTimeMillis();
		
		for(int i=0; i<purgeSize; i++) {
			m = (Message)qreceiver.receiveNoWait();
			if(m == null) {
				System.out.println(">> No more Message in Queue - " + queueName);
				System.out.println(">> Stop Purge.");
				break;
			}
			
			purgeCount++;
			
			System.out.println("\n>> purge "+(i+1));
			
			if(isLogging) {
				/*
				System.out.println("Message ID " + m.getJMSMessageID() +
				               " delivered " + new Date(m.getJMSTimestamp()) +
				               " to " + m.getJMSDestination());
				System.out.print("\tExpires        ");
	        
				if (m.getJMSExpiration() > 0) {
					System.out.println( new Date( m.getJMSExpiration()));
				}
				else {
					System.out.println("never");
				}
	        
				System.out.println("\tPriority        " + m.getJMSPriority());
				System.out.println("\tMode            " + (
	                      m.getJMSDeliveryMode() == DeliveryMode.PERSISTENT ?
	                                       "PERSISTENT" : "NON_PERSISTENT"));
				System.out.println("\tCorrelation ID  " + m.getJMSCorrelationID());
				System.out.println("\tReply to        " + m.getJMSReplyTo());
				System.out.println("\tMessage type    " + m.getJMSType());
				System.out.println("\tMessage BizCode " + m.getStringProperty("BizCode"));
	        	
				if (m instanceof TextMessage) {
					System.out.println("\tTextMessage    \"" +
							((TextMessage)m).getText() + "\"");
				}
				*/
				if(m instanceof ObjectMessage) {
					al.add(m);
				}
			}
		}
		System.out.println("----------------------------------------------------------------");
		System.out.println(">> Purge "+purgeCount+" messages completed : connect time("+cTime+") ms, purge time (" 
				+ (System.currentTimeMillis() - sTime) +") ms");
		
		System.out.println("----------------------------------------------------------------");
		
		return al;
	}
	
	catch( Exception e ) {
		throw e;
	}
	finally {
		try {
			if(qreceiver != null) qreceiver.close();
			if(qsession != null) qsession.close();
			if(qcon     != null) qcon.close();
		}
		catch(Exception ex) {}
	}
}%>
<%
	ArrayList al = null;
	String queueName = request.getParameter("queueName");
    String maxCount = request.getParameter("maxCount");
    String fromTime = request.getParameter("fromTime");
    String toTime = request.getParameter("toTime");
    

    String selector = request.getParameter("selector");

    String actionType = request.getParameter("actionType");

	String[][] monitorDataTotal = null;
	String[][] monitorData = null;
	
	String timeSelector = "";
	String mSelector = "";
	if( (fromTime != null && fromTime.length() == 14) && (toTime != null && toTime.length() == 14)) {
		SimpleDateFormat	SDF_YYYYMMDDHHMMSS_NO_MARK = new SimpleDateFormat( "yyyyMMddHHmmss");
		Date fDate= SDF_YYYYMMDDHHMMSS_NO_MARK.parse(fromTime);
		Date tDate= SDF_YYYYMMDDHHMMSS_NO_MARK.parse(toTime);
		Calendar calendar = new GregorianCalendar(TimeZone.getTimeZone("GMT+09:00"),Locale.KOREA);
		calendar.setTime (fDate);
        Long ftimeMili = calendar.getTimeInMillis();
        
        calendar.setTime (tDate);        
        Long ttimeMili = calendar.getTimeInMillis();
        
		timeSelector = "JMSTimestamp  BETWEEN " + ftimeMili + " AND " + ttimeMili ;
	
		if(selector != null && selector.trim().length() > 0) {
			mSelector = selector + " AND " + timeSelector;
		}
		else {
			mSelector = timeSelector;
		}
	}
	
	FCQueueReceiverManager man = FCQueueReceiverManager.getInstance();
	System.out.println("actionType    = " + actionType);
	System.out.println("queueName     = " + queueName);
	System.out.println("maxCount      = " + maxCount);
	System.out.println("selector      = " + selector);
	System.out.println("fromTime      = " + fromTime);
	System.out.println("toTime        = " + toTime);
	System.out.println("mSelector     = " + mSelector);
	
	String errorMsg = null;
	
	try {
		if("DISPLAY".equals(actionType)) {
			System.out.println("DISPLAY : queueName = " + queueName);
			int mCount = Integer.parseInt(maxCount);
			al = displayQueue(queueName, mSelector, mCount);
		}
		else if("PURGE".equals(actionType)) {
			System.out.println("PURGE : queueName = " + queueName);
			int mCount = Integer.parseInt(maxCount);
			al = purgeQueue(queueName, mSelector, mCount, true);
		}
		else {
			System.out.println("Unhandled Action " + actionType);
		}
		
		
	} catch(Exception e) {
		errorMsg = e.getMessage();
	}
		
%>
<html>
    <head>
        <title>
            FC Queue Purger
        </title>
        <script>
        function doAction() {
            document.frm.submit();
        }

        function doDisplay() {
            document.frm.actionType.value="DISPLAY";
            document.frm.submit();
        }

        function doPurge() {
            document.frm.actionType.value="PURGE";
            document.frm.submit();
        }

        </script>
    </head>
    <body>
        <p style="font-size:12pt;">
        <b>FC Queue Receiver Manager</b>
        </p>
        <form name="frm" action="">
        <input type="hidden" name="actionType" value="">
        <table border='0' width="800" >
        <tr>
        <td colspan="5" align='left'>
<%
	if(errorMsg != null) {
%>
<font color=red>Error : <%= errorMsg %></font>
<%
	}
%>        	
        	</td>
        </tr>
        <tr>
        <td width="200" align='left'>* Queue Name</td>
        <td align='left'><input type="text" name="queueName" size='40' value="<%= queueName==null?"":queueName %>" ></td>
        </tr>
        <td width="200" align='left'>* Message Count</td>
        <td align='left'><input type="text" name="maxCount" size='40' value="<%= maxCount==null?"":maxCount %>" ></td>
        </tr>
        <tr>
        <td width="200" align='left'>Selector</td>
        <td align='left'><input type="text" name="selector" size='40' value="<%= selector==null?"":selector %>" ></td>
        </tr>
        <tr>
        <td width="200" align='left'>Selector Time(yyyyMMddHHmmss)</td>
        <td align='left'>
        <input type="text" name="fromTime" size='14' maxlength='14' value="<%= fromTime==null?"":fromTime %>" >
        <input type="text" name="toTime" size='14' maxlength='14' value="<%= toTime==null?"":toTime %>" >
        </td>
        </tr>
        <tr>
        <td colspan="2" align='left'>Selector keys( EAIBWKCLS, EAISVCCD, OSIDINSTCD )</td>
        </tr>
        <tr>
  		<td colspan="2" align='right'>
           <input type="button" value="DISPLAY" onclick="doDisplay()">
            <input type="button" value="PURGE" onclick="doPurge()">
        </td>
        </tr>
        
        </table><br>
        <table width="800" border=0 bgcolor='black' cellpadding="1" cellspacing="1">
        <tr bgcolor='white'>
           <td align='center' width='300' bgcolor="#ccccff">JMS MsgID</td>
           <td align='center' width='300' bgcolor="#ccccff">JMS delivered</td>
           <td align='center' width='200' bgcolor="#ccccff">BwkCls</td>
		   <td align='center' width='200' bgcolor="#ccccff">EAISvcCd</td>
        </tr>
<%
	
	if(al == null || al.size() == 0) {
%>
        <tr bgcolor='white'>
            <td align='left' colspan="4" bgcolor="#ffffff">No Message in Queue&nbsp;</td>
        </tr>
<%
	}
	else {
		try {
			for(int i=0; i<al.size(); i++) {
				Object o = al.get(i);
				EAIMessage msg = null;
				ObjectMessage om = null;
				if(o instanceof ObjectMessage) {
					om = (ObjectMessage)o;
					msg = (EAIMessage)om.getObject();
			
%>
        <tr bgcolor='white'>
            <td align='left' bgcolor="#ffffff"><%= om.getJMSMessageID() %>&nbsp;</td>
            <td align='left' bgcolor="#ffffff"><%= new Date(om.getJMSTimestamp()) %>&nbsp;</td>
            <td align='left' bgcolor="#ffffff"><%= msg.getBwkCls() %>&nbsp;</td>
            <td align='left' bgcolor="#ffffff"><%= msg.getEAISvcCd() %>&nbsp;</td>
        </tr>
<%
		
				}
			}
		} catch(Exception e) {
			out.println(e.getMessage());
		}
	}
%>
        </table><br>
        
        </form>
    </body>
</html>