/*
 * The contents of this file are subject to the terms 
 * of the Common Development and Distribution License 
 * (the License).  You may not use this file except in
 * compliance with the License.
 * 
 * You can obtain a copy of the license at 
 * https://glassfish.dev.java.net/public/CDDLv1.0.html or
 * glassfish/bootstrap/legal/CDDLv1.0.txt.
 * See the License for the specific language governing 
 * permissions and limitations under the License.
 * 
 * When distributing Covered Code, include this CDDL 
 * Header Notice in each file and include the License file 
 * at glassfish/bootstrap/legal/CDDLv1.0.txt.  
 * If applicable, add the following below the CDDL Header, 
 * with the fields enclosed by brackets [] replaced by
 * you own identifying information: 
 * "Portions Copyrighted [year] [name of copyright owner]"
 * 
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 */

package com.sun.enterprise.cli.commands.monitor;

import com.sun.enterprise.cli.framework.*;
import com.sun.appserv.management.monitor.*;
import com.sun.appserv.management.monitor.statistics.*;
import javax.management.j2ee.statistics.*;
import com.sun.appserv.management.j2ee.statistics.*;
import javax.management.MBeanServerConnection;
import com.sun.enterprise.util.i18n.StringManager;
import com.sun.appserv.management.util.misc.MapUtil;
import java.util.Map;
import java.util.HashMap;
import java.util.Timer;
import java.io.File;

public class HttpListenerMonitorTask extends MonitorTask
{
    private final String displayFormat = "%1$-4s %2$-4s %3$-4s %4$-4s %5$-4s %6$-4s "+
                                         "%7$-4s %8$-4s %9$-4s %10$-4s %11$-4s %12$-4s %13$-4s "+
                                         "%14$-4s %15$-4s %16$-4s %17$-4s %18$-4s %19$-4s "+
                                         "%20$-4s %21$-4s %22$-4s %23$-4s %24$-4s %25$-4s %26$-4s";

    public HttpListenerMonitorTask(final ServerRootMonitor srm, final String filter, final Timer timer,
                                   final boolean verbose, final File fileName)
        throws MonitorTaskException
    {
        super(srm, filter, timer, verbose, fileName);
        final HTTPServiceMonitor httpserviceMonitor = srm.getHTTPServiceMonitor();
        if (httpserviceMonitor == null) 
            throw new MonitorTaskException("Unable to monitor httplistener");
        
        final Map<String,HTTPListenerMonitor> httpListenerMap = httpserviceMonitor.getHTTPListenerMonitorMap();
        if (httpListenerMap == null)
            throw new MonitorTaskException("Unable to monitor httplistener");
        
        final String[] keys = MapUtil.getKeyStrings(httpListenerMap);
        if (this.filter == null)
        {
            checkForNumberOfElements(keys);
            this.filter = keys[0];
        }
        else {
            if (!httpListenerMap.containsKey(this.filter)) {
                throw new MonitorTaskException(this.filter + " does not exist");
            }
        }
        final String title = String.format("%1$60s", "HTTP Listener Monitoring " + this.filter);
        System.out.println(title);
        displayHeader();        
    }
    

    public void run()
    {
        if (srm == null) {
            super.cancelMonitorTask();
            return;
        }
        

        final HTTPServiceMonitor httpserviceMonitor = srm.getHTTPServiceMonitor();
        if (httpserviceMonitor == null) {
            cancelMonitorTask();
            return;
        }
        

        final Map<String,HTTPListenerMonitor> httpListenerMap = httpserviceMonitor.getHTTPListenerMonitorMap();
        if (httpListenerMap == null || httpListenerMap.size()<1) {
            cancelMonitorTask();
            return;
        }
        
        final HTTPListenerMonitor httpListenerMonitor = httpListenerMap.get(filter);
        if (httpListenerMonitor == null) {
            cancelMonitorTask();
            return;
        }
        
        final HTTPListenerStats httpListenerStats = httpListenerMonitor.getHTTPListenerStats();

        if (verbose && counter == NUM_ROWS)
        {
            displayHeader();
            counter = 0;  //reset to 0
        }
        displayData(httpListenerStats);
        if (verbose) counter++;
    }

    
    private void displayHeader()
    {
        final String header = String.format(displayFormat,
                                            "br","bs","c200","c2xx","c302","c304","c3xx","c400",
                                            "c401","c403","c404","c4xx","c503","c5xx","coc","co",
                                            "ctc","ctb","ec","moc","mst","mt","mtm","mst","pt","rc");
        System.out.println(header);
        if (fileName != null)
        {
            writeToFile("BytesReceived,BytesSent,Count200,Count2xx,Count302,Count304,Count3xx,Count400"+
                        "Count401,Count403,Count404,Count4xx,Count503,Count5xx,CountOpenConnections,"+
                        "CountOther,CurrentThreadCount,CurrentThreadsBusy,ErrorCount,MaxOpenConnections"+
                        "MaxSpareThreads,MaxThreads,MaxTime,MaxSpareThreads,ProcessingTime,RequestCount");
        }
    }

    
    private void displayData(final HTTPListenerStats hls)
    {
        final String data = String.format(displayFormat,
                                          hls.getBytesReceived().getCount(),
                                          hls.getBytesSent().getCount(),
                                          hls.getCount200().getCount(),
                                          hls.getCount2xx().getCount(),
                                          hls.getCount302().getCount(),
                                          hls.getCount304().getCount(),
                                          hls.getCount3xx().getCount(),
                                          hls.getCount400().getCount(),
                                          hls.getCount401().getCount(),
                                          hls.getCount403().getCount(),
                                          hls.getCount404().getCount(),
                                          hls.getCount4xx().getCount(),
                                          hls.getCount503().getCount(),
                                          hls.getCount5xx().getCount(),
                                          hls.getCountOpenConnections().getCount(),
                                          hls.getCountOther().getCount(),
                                          hls.getCurrentThreadCount().getCount(),
                                          hls.getCurrentThreadsBusy().getCount(),
                                          hls.getErrorCount().getCount(),
                                          hls.getMaxOpenConnections().getCount(),
                                          hls.getMaxSpareThreads().getCount(),
                                          hls.getMaxThreads().getCount(),
                                          hls.getMaxTime().getCount(),
                                          hls.getMinSpareThreads().getCount(),
                                          hls.getProcessingTime().getCount(),
                                          hls.getRequestCount().getCount());
        System.out.println(data);
        if (fileName != null)
        {
            final String fileData = String.format("%1$s,%2$s,%3$s,%4$s,%5$s,%6$s,%7$s,%8$s,"+
                                              "%9$s,%10$s,%11$s,%12$s,%13$s,%14$s,%15$s,"+
                                              "%16$s,%17$s,%18$s,%19$s,%20$s,%21$s,%22$s,"+
                                              "%23$s,%24$s,%25$s,%26$s",
                                              hls.getBytesReceived().getCount(),
                                              hls.getBytesSent().getCount(),
                                              hls.getCount200().getCount(),
                                              hls.getCount2xx().getCount(),
                                              hls.getCount302().getCount(),
                                              hls.getCount304().getCount(),
                                              hls.getCount3xx().getCount(),
                                              hls.getCount400().getCount(),
                                              hls.getCount401().getCount(),
                                              hls.getCount403().getCount(),
                                              hls.getCount404().getCount(),
                                              hls.getCount4xx().getCount(),
                                              hls.getCount503().getCount(),
                                              hls.getCount5xx().getCount(),
                                              hls.getCountOpenConnections().getCount(),
                                              hls.getCountOther().getCount(),
                                              hls.getCurrentThreadCount().getCount(),
                                              hls.getCurrentThreadsBusy().getCount(),
                                              hls.getErrorCount().getCount(),
                                              hls.getMaxOpenConnections().getCount(),
                                              hls.getMaxSpareThreads().getCount(),
                                              hls.getMaxThreads().getCount(),
                                              hls.getMaxTime().getCount(),
                                              hls.getMinSpareThreads().getCount(),
                                              hls.getProcessingTime().getCount(),
                                              hls.getRequestCount().getCount());
            writeToFile(fileData);
        }
    }

    
    public void displayDetails()
    {
        
        System.out.println("******************************************************************************************");
        System.out.println("* br   = Cumulative value of the Bytes received by each of the Request Processors        *");
        System.out.println("* bs   = Cumulative value of the Bytes sent by each of the Request Processors            *");
        System.out.println("* c200 = Number of responses with a status code equal to 200                             *");
        System.out.println("* c2xx = Number of responses with a status code in the 2xx range                         *");
        System.out.println("* c302 = Number of responses with a status code equal to 302                             *");
        System.out.println("* c304 = Number of responses with a status code equal to 304                             *");
        System.out.println("* c3xx = Number of responses with a status code in the 3xx range                         *");
        System.out.println("* c400 = Number of responses with a status code equal to 400                             *");
        System.out.println("* c401 = Number of responses with a status code equal to 401                             *");
        System.out.println("* c403 = Number of responses with a status code equal to 403                             *");
        System.out.println("* c404 = Number of responses with a status code equal to 404                             *");
        System.out.println("* c4xx = Number of responses with a status code equal to 4xx                             *");
        System.out.println("* c504 = Number of responses with a status code equal to 504                             *");
        System.out.println("* c5xx = Number of responses with a status code equal to 5xx                             *");
        System.out.println("* coc  = Number of open connections                                                      *");
        System.out.println("* co   = Number of responses with a status code outside the 2xx, 3xx, 4xx, and 5xx range *");
        System.out.println("* ctc  = Number of request processing threads currently in the listener thread pool      *");
        System.out.println("* ctb  = Number of request processing threads currently in use in the listener thread    *");
        System.out.println("*        pool serving requests                                                           *");
        System.out.println("* ec   = Number of responses with a status code equal to 400                             *");
        System.out.println("* moc  = Maximum number of open connections                                              *");
        System.out.println("* mst  = Minimum number of request processing threads that will be created at listener   *");
        System.out.println("*        startup time and maintained as spare threads above the current thread count     *");
        System.out.println("* pt   = Cumulative value of the times taken to process each request. The processing     *");
        System.out.println("*        time is the average of request processing times over the request count          *");
        System.out.println("* rc   = Cumulative number of the requests processed so far                              *");
        System.out.println("******************************************************************************************");        
    }


}
    
    

