geronimo-scm mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From ecr...@apache.org
Subject svn commit: r613704 - in /geronimo/server/trunk/applications/monitoring: ./ agent-ear/ agent-ejb/ agent-ejb/src/main/java/org/apache/geronimo/monitoring/ agent-ejb/src/main/java/org/apache/geronimo/monitoring/snapshot/ agent-jar/ agent-jar/src/ agent-j...
Date Mon, 21 Jan 2008 00:15:50 GMT
Author: ecraig
Date: Sun Jan 20 16:15:47 2008
New Revision: 613704

URL: http://svn.apache.org/viewvc?rev=613704&view=rev
Log:
GERONIMO-3766: monitoring agent should be separated into mejb, jmx, and jar utility classes \n Patch by Viet Nguyen

Added:
    geronimo/server/trunk/applications/monitoring/agent-jar/
    geronimo/server/trunk/applications/monitoring/agent-jar/LICENSE.txt
    geronimo/server/trunk/applications/monitoring/agent-jar/NOTICE.txt
    geronimo/server/trunk/applications/monitoring/agent-jar/pom.xml
    geronimo/server/trunk/applications/monitoring/agent-jar/src/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/MBeanHelper.java
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotConfigXMLBuilder.java
    geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotDBHelper.java
Removed:
    geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/MBeanHelper.java
    geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotConfigXMLBuilder.java
    geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotDBHelper.java
Modified:
    geronimo/server/trunk/applications/monitoring/agent-ear/pom.xml
    geronimo/server/trunk/applications/monitoring/agent-ejb/pom.xml
    geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/MasterRemoteControl.java
    geronimo/server/trunk/applications/monitoring/pom.xml

Modified: geronimo/server/trunk/applications/monitoring/agent-ear/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-ear/pom.xml?rev=613704&r1=613703&r2=613704&view=diff
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-ear/pom.xml (original)
+++ geronimo/server/trunk/applications/monitoring/agent-ear/pom.xml Sun Jan 20 16:15:47 2008
@@ -59,6 +59,12 @@
                             <artifactId>agent-ejb</artifactId>
                             <bundleFileName>agent-ejb.jar</bundleFileName>
                         </ejbModule>
+                        <jarModule>
+                            <groupId>${pom.groupId}</groupId>
+                            <artifactId>agent-jar</artifactId>
+                            <bundleDir>lib</bundleDir>
+                            <!--includeInApplicationXml>true</includeInApplicationXml-->
+                        </jarModule>
                     </modules>
                     <resourcesDir>${project.build.outputDirectory}</resourcesDir>
                         <archive>
@@ -70,6 +76,7 @@
         </plugins>
     </build>
 </project>
+
 
 
 

Modified: geronimo/server/trunk/applications/monitoring/agent-ejb/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-ejb/pom.xml?rev=613704&r1=613703&r2=613704&view=diff
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-ejb/pom.xml (original)
+++ geronimo/server/trunk/applications/monitoring/agent-ejb/pom.xml Sun Jan 20 16:15:47 2008
@@ -45,31 +45,28 @@
             <artifactId>xmlbeans</artifactId>
             <scope>provided</scope>
         </dependency>
-
         <dependency>
             <groupId>org.apache.geronimo.specs</groupId>
             <artifactId>geronimo-annotation_1.0_spec</artifactId>
             <scope>provided</scope>
         </dependency>
-
         <dependency>
             <groupId>org.apache.geronimo.specs</groupId>
             <artifactId>geronimo-j2ee-management_1.1_spec</artifactId>
             <scope>provided</scope>
         </dependency>
-
         <dependency>
             <groupId>org.apache.geronimo.specs</groupId>
             <artifactId>geronimo-ejb_3.0_spec</artifactId>
             <scope>provided</scope>
         </dependency>
-        <!--
-       <dependency>
-           <groupId>commons-logging</groupId>
-           <artifactId>commons-logging</artifactId>
-           <version>1.0.4</version>
-       </dependency> -->
+        <dependency>
+            <groupId>org.apache.geronimo.plugins.monitoring</groupId>
+            <artifactId>agent-jar</artifactId>
+            <version>2.1-SNAPSHOT</version>
+        </dependency>
     </dependencies>
 </project>
+
 
 

Modified: geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/MasterRemoteControl.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/MasterRemoteControl.java?rev=613704&r1=613703&r2=613704&view=diff
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/MasterRemoteControl.java (original)
+++ geronimo/server/trunk/applications/monitoring/agent-ejb/src/main/java/org/apache/geronimo/monitoring/MasterRemoteControl.java Sun Jan 20 16:15:47 2008
@@ -95,6 +95,7 @@
     private SnapshotDBHelper snapshotDBHelper;
 
     public MasterRemoteControl() {
+        
     }
 
     @PostConstruct
@@ -280,9 +281,7 @@
      */ 
     @RolesAllowed("mejbuser")
     public ArrayList<HashMap<String, HashMap<String, Object>>> fetchSnapshotData(Integer numberOfSnapshot, Integer everyNthSnapshot) {
-        ArrayList<HashMap<String, HashMap<String, Object>>> retval = 
-            (ArrayList<HashMap<String, HashMap<String, Object>>>)snapshotDBHelper.fetchData(numberOfSnapshot, everyNthSnapshot);
-        return retval;
+        return (ArrayList<HashMap<String, HashMap<String, Object>>>)snapshotDBHelper.fetchData(numberOfSnapshot, everyNthSnapshot);
     }
     
     /**
@@ -294,9 +293,7 @@
      */
     @RolesAllowed("mejbuser")
     public HashMap<String, HashMap<String, Long>> fetchMaxSnapshotData(Integer numberOfSnapshot) {
-        HashMap<String, HashMap<String, Long>> retval = 
-            (HashMap<String, HashMap<String, Long>>)snapshotDBHelper.fetchMaxSnapshotData(numberOfSnapshot);
-        return retval;
+        return (HashMap<String, HashMap<String, Long>>)snapshotDBHelper.fetchMaxSnapshotData(numberOfSnapshot);
     }
 
     /**
@@ -308,9 +305,7 @@
      */
     @RolesAllowed("mejbuser")
     public HashMap<String, HashMap<String, Long>> fetchMinSnapshotData(Integer numberOfSnapshot) {
-        HashMap<String, HashMap<String, Long>> retval = 
-            (HashMap<String, HashMap<String, Long>>)snapshotDBHelper.fetchMinSnapshotData(numberOfSnapshot);
-        return retval;
+        return (HashMap<String, HashMap<String, Long>>)snapshotDBHelper.fetchMinSnapshotData(numberOfSnapshot);
     }
     
     /**

Added: geronimo/server/trunk/applications/monitoring/agent-jar/LICENSE.txt
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-jar/LICENSE.txt?rev=613704&view=auto
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-jar/LICENSE.txt (added)
+++ geronimo/server/trunk/applications/monitoring/agent-jar/LICENSE.txt Sun Jan 20 16:15:47 2008
@@ -0,0 +1,203 @@
+
+                                 Apache License
+                           Version 2.0, January 2004
+                        http://www.apache.org/licenses/
+
+   TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+   1. Definitions.
+
+      "License" shall mean the terms and conditions for use, reproduction,
+      and distribution as defined by Sections 1 through 9 of this document.
+
+      "Licensor" shall mean the copyright owner or entity authorized by
+      the copyright owner that is granting the License.
+
+      "Legal Entity" shall mean the union of the acting entity and all
+      other entities that control, are controlled by, or are under common
+      control with that entity. For the purposes of this definition,
+      "control" means (i) the power, direct or indirect, to cause the
+      direction or management of such entity, whether by contract or
+      otherwise, or (ii) ownership of fifty percent (50%) or more of the
+      outstanding shares, or (iii) beneficial ownership of such entity.
+
+      "You" (or "Your") shall mean an individual or Legal Entity
+      exercising permissions granted by this License.
+
+      "Source" form shall mean the preferred form for making modifications,
+      including but not limited to software source code, documentation
+      source, and configuration files.
+
+      "Object" form shall mean any form resulting from mechanical
+      transformation or translation of a Source form, including but
+      not limited to compiled object code, generated documentation,
+      and conversions to other media types.
+
+      "Work" shall mean the work of authorship, whether in Source or
+      Object form, made available under the License, as indicated by a
+      copyright notice that is included in or attached to the work
+      (an example is provided in the Appendix below).
+
+      "Derivative Works" shall mean any work, whether in Source or Object
+      form, that is based on (or derived from) the Work and for which the
+      editorial revisions, annotations, elaborations, or other modifications
+      represent, as a whole, an original work of authorship. For the purposes
+      of this License, Derivative Works shall not include works that remain
+      separable from, or merely link (or bind by name) to the interfaces of,
+      the Work and Derivative Works thereof.
+
+      "Contribution" shall mean any work of authorship, including
+      the original version of the Work and any modifications or additions
+      to that Work or Derivative Works thereof, that is intentionally
+      submitted to Licensor for inclusion in the Work by the copyright owner
+      or by an individual or Legal Entity authorized to submit on behalf of
+      the copyright owner. For the purposes of this definition, "submitted"
+      means any form of electronic, verbal, or written communication sent
+      to the Licensor or its representatives, including but not limited to
+      communication on electronic mailing lists, source code control systems,
+      and issue tracking systems that are managed by, or on behalf of, the
+      Licensor for the purpose of discussing and improving the Work, but
+      excluding communication that is conspicuously marked or otherwise
+      designated in writing by the copyright owner as "Not a Contribution."
+
+      "Contributor" shall mean Licensor and any individual or Legal Entity
+      on behalf of whom a Contribution has been received by Licensor and
+      subsequently incorporated within the Work.
+
+   2. Grant of Copyright License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      copyright license to reproduce, prepare Derivative Works of,
+      publicly display, publicly perform, sublicense, and distribute the
+      Work and such Derivative Works in Source or Object form.
+
+   3. Grant of Patent License. Subject to the terms and conditions of
+      this License, each Contributor hereby grants to You a perpetual,
+      worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+      (except as stated in this section) patent license to make, have made,
+      use, offer to sell, sell, import, and otherwise transfer the Work,
+      where such license applies only to those patent claims licensable
+      by such Contributor that are necessarily infringed by their
+      Contribution(s) alone or by combination of their Contribution(s)
+      with the Work to which such Contribution(s) was submitted. If You
+      institute patent litigation against any entity (including a
+      cross-claim or counterclaim in a lawsuit) alleging that the Work
+      or a Contribution incorporated within the Work constitutes direct
+      or contributory patent infringement, then any patent licenses
+      granted to You under this License for that Work shall terminate
+      as of the date such litigation is filed.
+
+   4. Redistribution. You may reproduce and distribute copies of the
+      Work or Derivative Works thereof in any medium, with or without
+      modifications, and in Source or Object form, provided that You
+      meet the following conditions:
+
+      (a) You must give any other recipients of the Work or
+          Derivative Works a copy of this License; and
+
+      (b) You must cause any modified files to carry prominent notices
+          stating that You changed the files; and
+
+      (c) You must retain, in the Source form of any Derivative Works
+          that You distribute, all copyright, patent, trademark, and
+          attribution notices from the Source form of the Work,
+          excluding those notices that do not pertain to any part of
+          the Derivative Works; and
+
+      (d) If the Work includes a "NOTICE" text file as part of its
+          distribution, then any Derivative Works that You distribute must
+          include a readable copy of the attribution notices contained
+          within such NOTICE file, excluding those notices that do not
+          pertain to any part of the Derivative Works, in at least one
+          of the following places: within a NOTICE text file distributed
+          as part of the Derivative Works; within the Source form or
+          documentation, if provided along with the Derivative Works; or,
+          within a display generated by the Derivative Works, if and
+          wherever such third-party notices normally appear. The contents
+          of the NOTICE file are for informational purposes only and
+          do not modify the License. You may add Your own attribution
+          notices within Derivative Works that You distribute, alongside
+          or as an addendum to the NOTICE text from the Work, provided
+          that such additional attribution notices cannot be construed
+          as modifying the License.
+
+      You may add Your own copyright statement to Your modifications and
+      may provide additional or different license terms and conditions
+      for use, reproduction, or distribution of Your modifications, or
+      for any such Derivative Works as a whole, provided Your use,
+      reproduction, and distribution of the Work otherwise complies with
+      the conditions stated in this License.
+
+   5. Submission of Contributions. Unless You explicitly state otherwise,
+      any Contribution intentionally submitted for inclusion in the Work
+      by You to the Licensor shall be under the terms and conditions of
+      this License, without any additional terms or conditions.
+      Notwithstanding the above, nothing herein shall supersede or modify
+      the terms of any separate license agreement you may have executed
+      with Licensor regarding such Contributions.
+
+   6. Trademarks. This License does not grant permission to use the trade
+      names, trademarks, service marks, or product names of the Licensor,
+      except as required for reasonable and customary use in describing the
+      origin of the Work and reproducing the content of the NOTICE file.
+
+   7. Disclaimer of Warranty. Unless required by applicable law or
+      agreed to in writing, Licensor provides the Work (and each
+      Contributor provides its Contributions) on an "AS IS" BASIS,
+      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+      implied, including, without limitation, any warranties or conditions
+      of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+      PARTICULAR PURPOSE. You are solely responsible for determining the
+      appropriateness of using or redistributing the Work and assume any
+      risks associated with Your exercise of permissions under this License.
+
+   8. Limitation of Liability. In no event and under no legal theory,
+      whether in tort (including negligence), contract, or otherwise,
+      unless required by applicable law (such as deliberate and grossly
+      negligent acts) or agreed to in writing, shall any Contributor be
+      liable to You for damages, including any direct, indirect, special,
+      incidental, or consequential damages of any character arising as a
+      result of this License or out of the use or inability to use the
+      Work (including but not limited to damages for loss of goodwill,
+      work stoppage, computer failure or malfunction, or any and all
+      other commercial damages or losses), even if such Contributor
+      has been advised of the possibility of such damages.
+
+   9. Accepting Warranty or Additional Liability. While redistributing
+      the Work or Derivative Works thereof, You may choose to offer,
+      and charge a fee for, acceptance of support, warranty, indemnity,
+      or other liability obligations and/or rights consistent with this
+      License. However, in accepting such obligations, You may act only
+      on Your own behalf and on Your sole responsibility, not on behalf
+      of any other Contributor, and only if You agree to indemnify,
+      defend, and hold each Contributor harmless for any liability
+      incurred by, or claims asserted against, such Contributor by reason
+      of your accepting any such warranty or additional liability.
+
+   END OF TERMS AND CONDITIONS
+
+   APPENDIX: How to apply the Apache License to your work.
+
+      To apply the Apache License to your work, attach the following
+      boilerplate notice, with the fields enclosed by brackets "[]"
+      replaced with your own identifying information. (Don't include
+      the brackets!)  The text should be enclosed in the appropriate
+      comment syntax for the file format. We also recommend that a
+      file or class name and description of purpose be included on the
+      same "printed page" as the copyright notice for easier
+      identification within third-party archives.
+
+   Copyright [yyyy] [name of copyright owner]
+
+   Licensed under the Apache License, Version 2.0 (the "License");
+   you may not use this file except in compliance with the License.
+   You may obtain a copy of the License at
+
+       http://www.apache.org/licenses/LICENSE-2.0
+
+   Unless required by applicable law or agreed to in writing, software
+   distributed under the License is distributed on an "AS IS" BASIS,
+   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+   See the License for the specific language governing permissions and
+   limitations under the License.
+

Added: geronimo/server/trunk/applications/monitoring/agent-jar/NOTICE.txt
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-jar/NOTICE.txt?rev=613704&view=auto
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-jar/NOTICE.txt (added)
+++ geronimo/server/trunk/applications/monitoring/agent-jar/NOTICE.txt Sun Jan 20 16:15:47 2008
@@ -0,0 +1,5 @@
+Apache Geronimo 
+Copyright 2003-2006 The Apache Software Foundation
+
+This product includes software developed by
+The Apache Software Foundation (http://www.apache.org/).

Added: geronimo/server/trunk/applications/monitoring/agent-jar/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-jar/pom.xml?rev=613704&view=auto
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-jar/pom.xml (added)
+++ geronimo/server/trunk/applications/monitoring/agent-jar/pom.xml Sun Jan 20 16:15:47 2008
@@ -0,0 +1,56 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+    Licensed to the Apache Software Foundation (ASF) under one
+    or more contributor license agreements.  See the NOTICE file
+    distributed with this work for additional information
+    regarding copyright ownership.  The ASF licenses this file
+    to you under the Apache License, Version 2.0 (the
+    "License"); you may not use this file except in compliance
+    with the License.  You may obtain a copy of the License at
+    
+     http://www.apache.org/licenses/LICENSE-2.0
+    
+    Unless required by applicable law or agreed to in writing,
+    software distributed under the License is distributed on an
+    "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+    KIND, either express or implied.  See the License for the
+    specific language governing permissions and limitations
+    under the License.
+-->
+
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
+
+    <modelVersion>4.0.0</modelVersion>
+    <parent>
+        <groupId>org.apache.geronimo.plugins.monitoring</groupId>
+        <artifactId>monitoring</artifactId>
+        <version>2.1-SNAPSHOT</version>
+        <relativePath>../pom.xml</relativePath>
+    </parent>
+
+    <artifactId>agent-jar</artifactId>
+    <name>Geronimo Monitoring :: Monitoring Agent :: JAR</name>
+    <description>Geronimo Monitoring Agent Utility Library</description>
+
+    <dependencies>
+        <!-- TODO get rid of this -->
+        <dependency>
+            <groupId>org.apache.geronimo.modules</groupId>
+            <artifactId>geronimo-kernel</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <!--TODO GERONIMO-3719 hack fix -->
+        <dependency>
+            <groupId>org.apache.xmlbeans</groupId>
+            <artifactId>xmlbeans</artifactId>
+            <scope>provided</scope>
+        </dependency>
+        <dependency>
+            <groupId>org.apache.geronimo.specs</groupId>
+            <artifactId>geronimo-j2ee-management_1.1_spec</artifactId>
+            <scope>provided</scope>
+        </dependency>
+    </dependencies>
+</project>
+
+

Added: geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/MBeanHelper.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/MBeanHelper.java?rev=613704&view=auto
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/MBeanHelper.java (added)
+++ geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/MBeanHelper.java Sun Jan 20 16:15:47 2008
@@ -0,0 +1,59 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.monitoring;
+
+import java.net.URI;
+import java.util.HashSet;
+import java.util.Iterator;
+import java.util.Set;
+
+import javax.management.ObjectName;
+
+import org.apache.geronimo.kernel.Kernel;
+import org.apache.geronimo.kernel.KernelRegistry;
+
+import org.apache.geronimo.gbean.AbstractName;
+import org.apache.geronimo.gbean.AbstractNameQuery;
+
+public class MBeanHelper {
+    
+    /**
+     * Return all MBeans that provide stats
+     */
+    public static Set<String> getStatsProvidersMBeans(Set<String> allMBeans) {
+        Kernel kernel = KernelRegistry.getSingleKernel();
+        Set<String> result = new HashSet();
+
+        try {
+            for (Iterator it = allMBeans.iterator(); it.hasNext(); ) {
+                try {
+                    String mbeanName = (String) it.next();
+                    Boolean statisticsProvider = (Boolean) kernel.getAttribute(new ObjectName(mbeanName), "statisticsProvider");
+                    if (Boolean.TRUE.equals(statisticsProvider)) {
+                        result.add(mbeanName);
+                    }
+                } catch (Exception e) {
+                    // this will happen if there is not a matching attribute "statisticsProvider"
+                }
+            }
+        } catch(Exception e) {
+            e.printStackTrace();
+        }
+
+        return result;
+    }
+}

Added: geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotConfigXMLBuilder.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotConfigXMLBuilder.java?rev=613704&view=auto
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotConfigXMLBuilder.java (added)
+++ geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotConfigXMLBuilder.java Sun Jan 20 16:15:47 2008
@@ -0,0 +1,322 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.monitoring.snapshot;
+
+import java.io.File;
+import java.io.FileOutputStream;
+import java.util.ArrayList;
+
+import javax.xml.parsers.DocumentBuilder;
+import javax.xml.parsers.DocumentBuilderFactory;
+import javax.xml.parsers.ParserConfigurationException;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+import org.apache.xmlbeans.XmlCursor;
+import org.apache.xmlbeans.XmlObject;
+import org.w3c.dom.Document;
+import org.w3c.dom.Element;
+import org.w3c.dom.Node;
+import org.w3c.dom.NodeList;
+
+//import com.sun.org.apache.xml.internal.serialize.OutputFormat;
+//import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
+
+/**
+ * In charge of dealing with the XML processing of the snapshot's data.
+ */
+public class SnapshotConfigXMLBuilder {
+    private static Log log = LogFactory.getLog(SnapshotConfigXMLBuilder.class);
+    
+    private static final String pathToXML = 
+        System.getProperty("org.apache.geronimo.home.dir") + "/var/monitoring/snapshot-config.xml";
+    
+    private static final String SNAPSHOT_CONFIG = "snapshot-config";
+    private static final String DURATION = "duration";
+    private static final String RETENTION = "retention";
+    private static final String MBEAN = "mbean"; 
+    
+    /**
+     * @return A list of all mbean names that have been previously saved.
+     * These mbean names are those to keep track of for per snapshot.
+     */
+    public static ArrayList<String> getMBeanNames() {
+        ArrayList<String> mbeanList = new ArrayList<String>();
+        // get an instance of the document
+        Document doc = openDocument();
+        // get the root element node
+        Element rootElement = doc.getDocumentElement();
+        // get all children in the root node (i.e. all config properties)
+        NodeList configNodes = rootElement.getChildNodes();
+        // find the duration node and save it
+        for(int i = 0; i < configNodes.getLength(); i++) {
+            if(MBEAN.equals(configNodes.item(i).getNodeName())) {
+                mbeanList.add( configNodes.item(i).getTextContent() );
+            }
+        }
+        return mbeanList;
+    }
+    
+    /**
+     * Adds to the snapshot-config.xml another configuration element <mbean>
+     * in order to persistently keep track of all user requested statistics.
+     * If there is a duplicate, nothing will be done.
+     */
+    public static boolean removeMBeanName(String mbeanName) {
+        ArrayList<String> mbeanList = getMBeanNames();
+        // operate on the snapshot-config.xml if there exists the mbean name
+        if(mbeanList.contains(mbeanName)) {
+            // get an instance of the document
+            Document doc = openDocument();
+            // get the root element node
+            Element rootElement = doc.getDocumentElement();
+            // find the Node that represents the mbeanName
+            NodeList list = rootElement.getChildNodes();
+            for(int i = 0; i < list.getLength(); i++) {
+                // check the Node's text context for a match with mbeanName
+                if(list.item(i).getTextContent().equals(mbeanName)) {
+                    // remove the node from rootElement
+                    Node toRemoveNode = list.item(i);
+                    rootElement.removeChild(toRemoveNode);
+                    break;
+                }
+            }
+            // save the document
+            saveDocument(doc, pathToXML);
+            return true;
+        } else {
+            return false;
+        }
+    }
+
+    /**
+     * Removes from the snapshot-config.xml a configuration element <mbean>
+     * in order to persistently keep track of all user requested statistics.
+     * If there does not exist an instance of the mbeanNAme, nothing will be done.
+     */
+    public static boolean addMBeanName(String mbeanName) {
+        ArrayList<String> mbeanList = getMBeanNames();
+        if(mbeanList.contains(mbeanName)) {
+            return false;
+        } else {
+            // get an instance of the document
+            Document doc = openDocument();
+            // get the root element node
+            Element rootElement = doc.getDocumentElement();
+            // create <mbean> element
+            Element mbeanElement = doc.createElement(MBEAN);
+            mbeanElement.setTextContent(mbeanName);
+            // add <mbean> element to the rootElement
+            rootElement.appendChild(mbeanElement);
+            try {
+                Thread.sleep(1000);
+            } catch(Exception e) {
+                
+            }
+            // save the document
+            saveDocument(doc, pathToXML);
+            return true;
+        }
+    }
+    
+    /**
+     * Saves the duration of the snapshot as a configuration attribute
+     * @param duration
+     */
+    public static void saveDuration(long duration) {
+        saveAttribute(DURATION, duration);
+    }
+
+    /**
+     * Saves the retention of the snapshot as a configuration attribute
+     * @param retention
+     */
+    public static void saveRetention(int retention) {
+        saveAttribute(RETENTION, retention);
+    }
+    
+    /**
+     * Saves a generic attribute value into the node with text = attribute name.
+     * Creates one if there is not an instance of one.
+     * @param attrName
+     * @param attributeValue
+     */
+    private static void saveAttribute(String attrName, long attributeValue) {
+        Document doc = openDocument();
+        // get the root node        
+        Element rootElement = doc.getDocumentElement();
+        // get all children in the root node (i.e. all config properties)
+        NodeList configNodes = rootElement.getChildNodes();
+        // find the duration node and save it
+        boolean foundNode = false;
+        for(int i = 0; i < configNodes.getLength() && !foundNode; i++) {
+            Node configNode = configNodes.item(i);
+            if(attrName.equals(configNode.getNodeName())) {
+                // found a match
+                configNode.setTextContent(attributeValue + "");
+                foundNode = true;
+            }
+        }
+        // if there was not a duration node, make one
+        if(!foundNode) {
+            Element element = doc.createElement(attrName);
+            element.setTextContent(attributeValue + "");
+            rootElement.appendChild(element);
+        }
+        try {
+            Thread.sleep(1000);
+        } catch(Exception e) {
+            
+        }
+        log.info("***saving:  " + attrName + " = " + attributeValue);
+        // save the document to file
+        saveDocument(doc, pathToXML);
+    }
+    
+    /**
+     * Returns the value of the configuration attribute, defined by the key
+     * @param key
+     * @return
+     * @throws Exception
+     */
+    public static String getAttributeValue(String key) throws Exception {
+        // ensure that there exists the 'monitor' directory
+        ensureMonitorDir();
+        // get an instance of the document
+        Document doc = openDocument();
+        // get the root element node
+        Element rootElement = doc.getDocumentElement();
+        // get all children in the root node (i.e. all config properties)
+        NodeList configNodes = rootElement.getChildNodes();
+        // find the duration node and save it
+        for(int i = 0; i < configNodes.getLength(); i++) {
+            if(key.equals(configNodes.item(i).getNodeName())) {
+                return configNodes.item(i).getTextContent();
+            }
+        }
+        throw new Exception("[WARNING] " + key + " is not found in " + SNAPSHOT_CONFIG);
+    }
+    
+    /**
+     * Ensures that there is an existing XML file. Creates one if there
+     * does not exist one already. 
+     */
+    public static void checkXMLExists() {
+        File docFile = new File(pathToXML);
+        // create an XML document if it does not exist
+        if(!docFile.exists()) {
+            Document doc = setUpDocument( createDocument() );
+            saveDocument(doc, pathToXML);
+        }
+    }
+    
+    /**
+     * Prepares the root element for a document.
+     */
+    public static Document setUpDocument(Document document) {
+        // add <snapshot-config> tag as the root
+        Element rootElement = document.createElement("snapshot-config");
+        document.appendChild(rootElement);
+        return document;
+    }
+    
+    /**
+     * Creates an instance of a Document and returns it
+     */
+    public static Document createDocument() {
+        // get an instance of factory
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        try {
+            // get an instance of builder
+            DocumentBuilder db = dbf.newDocumentBuilder();
+            // create an instance of DOM
+            return db.newDocument();
+        } catch(ParserConfigurationException pce) {
+            log.error("Error while trying to instantiate DocumentBuilder", pce);
+        }
+        return null;
+    }
+    
+    /**
+     * Write the document object to the file location specified by
+     * the path.
+     */
+    public static void saveDocument(Document document, String path) {
+        try {
+            //TODO GERONIMO-3719.  Hack to use xmlbeans to write out xml instead of sun specific classes.
+            XmlObject xmlObject = XmlObject.Factory.parse(document.getDocumentElement());
+            xmlObject.save(new File(path));
+
+            // formatting the doc
+//            OutputFormat format = new OutputFormat(document);
+//            format.setIndenting(true);
+            // generate a file output
+//            XMLSerializer serializer = new XMLSerializer(new FileOutputStream(new File(path)), format);
+//            serializer.serialize(document);
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        }
+    }
+
+    /**
+     * Parses the XML document specified by the private member 'pathToXML'
+     * and stores the information in the a Document object
+     */
+    public static Document openDocument() {
+        // ensure that the XML file is there
+        checkXMLExists();
+        // get the factory
+        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
+        // continue to attempt to parse
+        while(true) {
+            try {
+                // Using factory get an instance of document builder
+                DocumentBuilder db = dbf.newDocumentBuilder();
+                // parse using builder to get DOM representation of the XML file
+                Document doc = db.parse(pathToXML);
+                return doc;
+            } catch(Exception e) {
+                // Either this file is being read/written to by snapshot thread
+                // or there is an UNKNOWN error
+                log.error(e.getMessage(), e);
+            }
+        }
+    }
+    
+    /**
+     * Checks to see if the GERONIMO_HOME/var/monitoring/ directory was made.
+     * If not, the method creates it.
+     */
+    public static void ensureMonitorDir() {
+        final String pathToDir = 
+            System.getProperty("org.apache.geronimo.home.dir") + "/var/monitoring/";
+        File dir = new File(pathToDir);
+        if(dir.exists() && dir.isDirectory()) {
+            // all good
+            return;
+        } else {
+            // make a directory
+            if(dir.mkdir()) {
+                // directory was successfully created
+                log.info("/var/monitoring directory created.");
+                return;
+            } else {
+                log.error("Could not make the directory " + pathToDir);
+            }
+        }
+    }
+}

Added: geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotDBHelper.java
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotDBHelper.java?rev=613704&view=auto
==============================================================================
--- geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotDBHelper.java (added)
+++ geronimo/server/trunk/applications/monitoring/agent-jar/src/main/java/org/apache/geronimo/monitoring/snapshot/SnapshotDBHelper.java Sun Jan 20 16:15:47 2008
@@ -0,0 +1,702 @@
+/**
+ *  Licensed to the Apache Software Foundation (ASF) under one or more
+ *  contributor license agreements.  See the NOTICE file distributed with
+ *  this work for additional information regarding copyright ownership.
+ *  The ASF licenses this file to You under the Apache License, Version 2.0
+ *  (the "License"); you may not use this file except in compliance with
+ *  the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
+package org.apache.geronimo.monitoring.snapshot;
+
+import java.sql.Connection;
+import java.sql.DriverManager;
+import java.sql.ResultSet;
+import java.sql.Statement;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Calendar;
+import java.util.Date;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.TreeMap;
+
+import javax.sql.DataSource;
+
+import org.apache.commons.logging.Log;
+import org.apache.commons.logging.LogFactory;
+
+public class SnapshotDBHelper {
+    private static Log log = LogFactory.getLog(SnapshotDBHelper.class);
+    // field attributes for the Statistics table in the DB
+    private static final String SNAPSHOT_TIME = "snapshot_time";
+    private static final String MBEANNAME = "mbeanName";
+    private static final String STATSVALUELIST = "statsValueList";
+    private static final String STATSNAMELIST = "statsNameList";
+    // Connection object used for DB interaction
+    private static Connection conn = null;
+    // Data Sources
+    private static DataSource activeDS = null;
+    private static DataSource archiveDS = null;
+    
+    public SnapshotDBHelper() {
+        
+    }
+    
+    public SnapshotDBHelper(DataSource activeDS, DataSource archiveDS) {
+        SnapshotDBHelper.activeDS = activeDS;
+        SnapshotDBHelper.archiveDS = archiveDS;
+    }
+    
+    /**
+     * @return A map: mbeanName --> ArrayList of statistic attributes for that mbean
+     */
+    public HashMap<String, ArrayList<String>> getAllSnapshotStatAttributes() {
+        openActiveConnection();
+        HashMap<String, ArrayList<String>> retval = new HashMap<String, ArrayList<String>>();
+        try {
+            Statement stmt = conn.createStatement();
+            String query = "SELECT DISTINCT mbeanName, statsNameList FROM MBeans";
+            ResultSet rs = stmt.executeQuery(query);
+            // add each mbean/statsValue combination to retval
+            while(rs.next()) {
+                String mbeanName = rs.getString(MBEANNAME);
+                String statsNameStr = rs.getString(STATSNAMELIST);
+                String[] statsNameList = statsNameStr.split(",");
+                ArrayList<String> mbeanAttributeList = new ArrayList<String>();
+                // copy from String[] to ArrayList<String>
+                for(int i = 0; i < statsNameList.length; i++) {
+                    mbeanAttributeList.add(statsNameList[i]);
+                }
+                retval.put(mbeanName, mbeanAttributeList);
+            }
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+        return retval;
+    }
+    
+    /**
+     * 
+     * @return The number of snapshots present in the active database
+     */
+    public Long getSnapshotCount() {
+        long retval = 0;
+        try {
+            openActiveConnection();
+            Statement stmt = conn.createStatement();
+            String query = "SELECT COUNT(DISTINCT snapshot_time) FROM Statistics";
+            ResultSet rs = stmt.executeQuery(query);
+            rs.next();
+            retval = rs.getLong(1);
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+        return new Long(retval);
+    }
+    
+    /**
+     * @param numberOfSnapshots - the number of latest snapshots to look at
+     * @return A hashmap which maps an mbean --> a hashmap with an attribute name and its value . All values will be the max.
+     */
+    public HashMap<String, HashMap<String, Long>> fetchMaxSnapshotData(Integer numberOfSnapshots) {
+        return fetchMaxOrMinSnapshotData(numberOfSnapshots, true);
+    }
+    /**
+     * @param numberOfSnapshots - the number of latest snapshots to look at
+     * @return A hashmap which maps an mbean --> a hashmap with an attribute name and its value . All values will be the min.
+     */    
+    public HashMap<String, HashMap<String, Long>> fetchMinSnapshotData(Integer numberOfSnapshots) {
+        return fetchMaxOrMinSnapshotData(numberOfSnapshots, false);
+    }
+    
+    /**
+     * @param numberOfSnapshots - the number of latest snapshots to look at.
+     * @param isMax - true if the result should be all maximum values. otherwise, false.
+     * @return A hashmap which maps an mbean --> a hashmap with an attribute name and its value . All values will be the min
+     * or max, depending on the isMax parameter.
+     */
+    private HashMap<String, HashMap<String, Long>> fetchMaxOrMinSnapshotData(Integer numberOfSnapshots, boolean isMax) {
+        openActiveConnection();
+        ResultSet snapshotTimeTable = fetchSnapshotTimesFromDB();
+        HashMap<String, HashMap<String, Long>> stats = new HashMap<String, HashMap<String, Long>>();
+        try {
+            // for each snapshot in the table
+            while(snapshotTimeTable.next()) {
+                Long snapshotTime = snapshotTimeTable.getLong(SNAPSHOT_TIME);
+                // retrieve the snapshot information by time
+                ResultSet snapshotData = fetchSnapshotDataFromDB(snapshotTime);
+                // for each statistic, perform a relaxation
+                while(snapshotData.next()) {
+                    String mbean = snapshotData.getString(MBEANNAME);
+                    // get map associated with mbean
+                    HashMap<String, Long> mbeanMap = stats.get(mbean);
+                    if(mbeanMap == null) {
+                        mbeanMap = new HashMap<String, Long>();
+                    }
+                    String[] statsNameList = snapshotData.getString(STATSNAMELIST).split(",");
+                    String[] statsValueList = snapshotData.getString(STATSVALUELIST).split(",");
+                    assert(statsNameList.length == statsValueList.length);
+                    // for each statname/statsvalue combo in an mbean
+                    for(int i = 0 ; i < statsNameList.length; i++) {
+                        String statsName = statsNameList[i];
+                        Long maxStatsValue = mbeanMap.get(statsName);
+                        // give maxStatsValue some value if there isn't one
+                        if(maxStatsValue == null) {
+                            if(isMax) {
+                                maxStatsValue = new Long(0);
+                            } else {
+                                maxStatsValue = Long.MAX_VALUE;
+                            }
+                        }
+                        // relax
+                        if(isMax) {
+                            maxStatsValue = new Long(Math.max(Long.parseLong(statsValueList[i]), maxStatsValue.longValue()));
+                        } else {
+                            maxStatsValue = new Long(Math.min(Long.parseLong(statsValueList[i]), maxStatsValue.longValue()));
+                        }
+                        // save name/value back into mbeanMap
+                        mbeanMap.put(statsName, maxStatsValue);
+                    }
+                    // save mbeanMap back into stats
+                    stats.put(mbean, mbeanMap);
+                }
+                
+                // compute the remaining snapshots left to look at
+                numberOfSnapshots--;
+                // discontinue once we have looked at numberOfSnapshots snapshots
+                if(numberOfSnapshots == 0) {
+                    break;
+                }
+            }
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+        return stats;
+    }
+    
+    /**
+     * @param ds
+     * @param aggregateStats
+     * @return Returns a boolean if the snapshot statistics were successfully added
+     * to the DB.
+     */
+    public boolean addSnapshotToDB(HashMap<String, HashMap<String, Long>> aggregateStats) {
+        boolean success = true;
+        // get the current time from 1970
+        String currTime = "";
+        currTime += (new Date()).getTime();
+        try {
+            // for each mbean
+            for(Iterator itt = aggregateStats.keySet().iterator(); itt.hasNext(); ) {
+                String mbean = (String)itt.next();
+                // prepare the statsNameList and statsValueList beforehand
+                String statsNameList = "", statsValueList = "";
+                for(Iterator<String> it = aggregateStats.get(mbean).keySet().iterator(); it.hasNext(); ) {
+                    String statsName = it.next();
+                    Long statsValue = aggregateStats.get(mbean).get(statsName);
+                    if(statsNameList.length() == 0 || statsValueList.length() == 0) {
+                        // do not add a comma because this is the first occurrence
+                        statsValueList += statsValue.toString();
+                        statsNameList += statsName;
+                    } else {
+                        // add a comma
+                        statsValueList += "," + statsValue.toString();
+                        statsNameList += "," + statsName;
+                    }
+                }
+                
+                // start talking to DB
+                openActiveConnection();
+                Statement stmt = conn.createStatement();
+                HashMap stats = aggregateStats.get(mbean);
+                //--------Ensure MBeans are in place
+                int mbeanId = getMBeanId(mbean); 
+                if(mbeanId != -1) {
+                    // mbean already exists in the db
+                } else {
+                    // doesn't exist in the db so add it
+                    // add mbean record to the db
+                    stmt.executeUpdate("INSERT INTO MBeans (mbeanName, statsNameList) VALUES ("+ surroundWithQuotes(mbean) + "," + surroundWithQuotes(statsNameList) + ")");
+                    mbeanId = getMBeanId(mbean);
+                }
+                
+                // insert the statistics into Statistics table
+                stmt.executeUpdate( prepareInsertSnapshotStatement(currTime, statsValueList, mbeanId) );
+                closeConnection();
+            }
+        } catch(Exception  e){
+            log.error(e.getMessage(), e);
+            success = false;
+        } finally {
+            closeConnection();
+        }
+        
+        // go through the archiving process
+        try {
+            int retentionDays = Integer.parseInt(SnapshotConfigXMLBuilder.getAttributeValue("retention"));
+            long retentionMillis = (long)(retentionDays) * 86400000; // convert from days to milliseconds
+            archiveSnapshots( Long.parseLong(currTime) - retentionMillis );
+        } catch(Exception e) {
+            log.warn("Cannot archive snapshots because attribute 'retention' is not present in snapshot-config.xml.");
+        }
+        return success;
+    }
+    
+    /**
+     * Moves records from the ActiveDB to the ArchiveDB. The records that are moved
+     * are those whose snapshot_times exceed the retention period
+     * @param cutOffTime - in milliseconds
+     */
+    private void archiveSnapshots(long cutOffTime) {
+        // for each successful update of Snapshots/Statistics table
+        // increment or decrement these counters to ensure that nothing is being 
+        // lost in between. If these counters are non-zero, some records have been
+        // lost.
+        int snapshotsOver = 0;
+        int statisticsOver = 0;
+        try {
+            openActiveConnection();
+            ResultSet overDueSnapshotTimes = getOverDueSnapshotTimes(cutOffTime);
+            ArrayList<Long> overdueTimes = new ArrayList<Long>();
+            // save overdue times into an array list for later usage
+            while(overDueSnapshotTimes.next()) {
+                overdueTimes.add(overDueSnapshotTimes.getLong(SNAPSHOT_TIME));
+            }
+            closeConnection();
+            // for each overdue snapshot time
+            // -transfer all records associated with that snaphot_time to ArchiveDB
+            for(int i = 0; i < overdueTimes.size(); i++) {
+                long snapshotTime = overdueTimes.get(i);
+                openActiveConnection();
+                ResultSet rsSnapshotData = fetchSnapshotDataFromDB(new Long(snapshotTime));
+                HashMap<String, HashMap<String, Long>> snapshotData = new HashMap<String,HashMap<String, Long>>();
+                while(rsSnapshotData.next()) {
+                    // extract values from sql table
+                    String mbeanName = rsSnapshotData.getString(MBEANNAME);
+                    String statsNameList = rsSnapshotData.getString(STATSNAMELIST);
+                    String statsValueList = rsSnapshotData.getString(STATSVALUELIST);
+                    Long snapshot_time = rsSnapshotData.getLong(SNAPSHOT_TIME);
+                    // get a connection to the archive db too
+                    Connection archiveConn = archiveDS.getConnection();
+                    Statement archiveStmt = archiveConn.createStatement();
+                    //--------Ensure MBeans are in place
+                    int mbeanId = getMBeanIdFromArchive(mbeanName); 
+                    if(mbeanId != -1) {
+                        // mbean already exists in the db
+                    } else {
+                        // doesn't exist in the db so add it
+                        // add mbean record to the db
+                        archiveStmt.executeUpdate("INSERT INTO MBeans (mbeanName, statsNameList) VALUES ("+ surroundWithQuotes(mbeanName) + ", " + surroundWithQuotes(statsNameList) + ")");
+                        mbeanId = getMBeanIdFromArchive(mbeanName);
+                    }
+                    // ensure Statistics table has record of mbeanId, snapshotId, statsValue, statsName
+                    String updateStr = prepareInsertSnapshotStatement(snapshot_time + "", statsValueList, mbeanId);
+                    statisticsOver += archiveStmt.executeUpdate( updateStr );
+                    // close connection to archiveDB
+                    archiveConn.close();
+                }
+                closeConnection();
+            }
+            // for each snapshot time, remove all instances that is associated with in 
+            // in the active DB
+            for(int i = 0; i < overdueTimes.size(); i++) {
+                long snapshotTime = overdueTimes.get(i);
+                openActiveConnection();
+                Statement stmt = conn.createStatement();
+                // remove from Statistics table
+                String statisticsUpdate = "DELETE FROM Statistics WHERE snapshot_time=" + snapshotTime;
+                statisticsOver -= stmt.executeUpdate(statisticsUpdate);
+                closeConnection();
+            }
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+        
+        // ensure that the transferring was good
+        if(snapshotsOver != 0) {
+            log.warn("Transferred snapshots was completed, but some things were lost.");
+        }
+        if(statisticsOver != 0) {
+            log.warn("Transferred statistics was completed, but some things were lost.");
+        }
+    }
+    
+    /**
+     * @param cutOffTime
+     * @return An SQL table contain a column of all the times that did not make the cutOffTime.
+     */
+    private ResultSet getOverDueSnapshotTimes(long cutOffTime) {
+        try {
+            Statement stmt = conn.createStatement();
+            String query = "SELECT DISTINCT snapshot_time FROM Statistics WHERE snapshot_time < " + cutOffTime;
+            return stmt.executeQuery(query);
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        }
+        return null;
+    }
+    
+    /**
+     * @param mbean
+     * @return The mbean id of the mbean from table ArchiveDB.MBean. Returns -1 if record does not exist.
+     */
+    private int getMBeanIdFromArchive(String mbean) throws Exception {
+        int retval = -1;
+        Connection archiveConn = archiveDS.getConnection();
+        Statement stmt = archiveConn.createStatement();
+        ResultSet rs = stmt.executeQuery("SELECT id FROM MBeans WHERE mbeanName=" + surroundWithQuotes(mbean));
+        if(rs.next()) {
+            retval = rs.getInt("id");
+        }
+        stmt.close();
+        archiveConn.close();
+        return retval;
+    }
+    
+    /**
+     * @param mbean
+     * @return The mbean id of the mbean from table ActiveDB.MBean. Returns -1 if record does not exist.
+     */
+    private int getMBeanId(String mbean) throws Exception {
+        int retval = -1;
+        Connection conn = activeDS.getConnection();
+        Statement stmt = conn.createStatement();
+        ResultSet rs = stmt.executeQuery("SELECT id FROM MBeans WHERE mbeanName=" + surroundWithQuotes(mbean));
+        if(rs.next()) {
+            retval = rs.getInt("id");
+        }
+        stmt.close();
+        conn.close();
+        return retval;
+    }
+    
+    /**
+     * @param snapshot_time
+     * @param statsValueList
+     * @param mbeanId
+     * @return Returns an SQL insert statement for one statistic given the correct information.
+     */
+    public String prepareInsertSnapshotStatement(String snapshot_time, String statsValueList, int mbeanId) {
+        String retval = "INSERT INTO Statistics (snapshot_time, statsValueList, mbeanId) VALUES (";
+        retval += snapshot_time;
+        retval += ",";
+        retval += surroundWithQuotes(statsValueList);
+        retval += ",";
+        retval += mbeanId;
+        retval += ")";
+        return retval;
+    }
+
+    /**
+     * @param s
+     * @return A String with ' at the beginning and end
+     */
+    private String surroundWithQuotes(String s) {
+        return "'" + s.trim() + "'";
+    }
+    
+    /**
+     * Fetches the data stored from the snapshot thread and returns
+     * it in a ArrayList with each element being a HashMap of the attribute
+     * mapping to the statistic. Grabs 'numberOfSnapshots' snapshots. Grabs 
+     * one snapshot per 'everyNthsnapshot'
+     * 
+     * @param numberOfSnapshot
+     * @param everyNthSnapshot
+     * @return ArrayList
+     */ 
+    public ArrayList<HashMap<String, HashMap<String, Object>>> fetchData(Integer numberOfSnapshot, 
+                                                                                Integer everyNthSnapshot) {
+        ArrayList<HashMap<String, HashMap<String, Object>>> stats = new ArrayList<HashMap<String, HashMap<String, Object>>>();
+        openActiveConnection();
+        // get all records in the database grouped and ordered by time
+        ResultSet table = fetchSnapshotTimesFromDB();
+        // iterate through the table and finds the times (which uniquely IDs a snapshot)
+        // that are wanted and queries the rest of the DB using the time as the condition
+        // (i.e. the ones that are in the c*n-th snapshot where c <= numberOfSnapshot
+        // and n == everyNthSnapshot)
+        int nthSnapshot = 0;
+        try {
+            while(table.next()) {
+                Long snapshotTime = table.getLong(SNAPSHOT_TIME);
+                // grab 0*nth, 1*nth, 2*nth snapshot up to min(numberOfSnapshot*everyNthSnapshot, size of the table)
+                if(nthSnapshot % everyNthSnapshot == 0) {
+                    HashMap<String, HashMap<String, Object>> snapshotData = packageSnapshotData(snapshotTime);
+                    stats.add( 0, snapshotData );
+                    numberOfSnapshot--;
+                }
+                nthSnapshot++;
+                // no more snapshots needs to be looked at, we have successfully acquired our goal
+                if(numberOfSnapshot == 0) {
+                    break;
+                }
+            }
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+        return stats;
+    }
+    
+    /**
+     * @param snapshotTime
+     * @return A hashmap in the form <String1, HashMap> where String1 is the mbean name
+     * and HashMap is a map containing a <String2, Object> where String2 is an attribute name
+     * and Object is the value. Additionally, if String is "times" then it maps to a HashMap
+     * containing snapshot_time and snapshot_date information.
+     */
+    private HashMap<String, HashMap<String, Object>> packageSnapshotData(Long snapshotTime) {
+        HashMap<String, HashMap<String, Object>> snapshotPkg = new HashMap<String, HashMap<String, Object>>();
+        openActiveConnection();
+        ResultSet snapshotData = fetchSnapshotDataFromDB(snapshotTime);
+        try {
+            // for each record save it somewhere in the snapshotPkg
+            while(snapshotData.next()) {
+                String currMBean = snapshotData.getString(MBEANNAME);
+                // get the information for the mbean defined by currMBean
+                HashMap<String, Object> mbeanInfo = snapshotPkg.get(currMBean);
+                if(mbeanInfo == null) {
+                    mbeanInfo = new HashMap<String, Object>();
+                }
+                // get statistics from resultset
+                String statsValueStr = snapshotData.getString(STATSVALUELIST);
+                String statsNameStr = snapshotData.getString(STATSNAMELIST);
+                String[] statsValueList = statsValueStr.split(",");
+                String[] statsNameList = statsNameStr.split(",");
+                assert(statsValueList.length == statsNameList.length);
+                // for each statsValue/statsName, save it
+                for(int i = 0 ; i < statsValueList.length; i++) {
+                    long statValue = Long.parseLong(statsValueList[i]);
+                    mbeanInfo.put(statsNameList[i], new Long(statValue));
+                }
+                // save the hashmap into the snapshotpkg
+                snapshotPkg.put(currMBean, mbeanInfo);
+            }
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+        // add the time and date
+        HashMap<String, Object> timeMap = new HashMap<String, Object>();
+        timeMap.put(SNAPSHOT_TIME, snapshotTime);
+        snapshotPkg.put("times", timeMap);
+        
+        return snapshotPkg;
+    }
+    
+    /**
+     * @param snapshotTime
+     * @return Returns a ResultSet with all statistic information that matches the snapshot_time.
+     */
+    private ResultSet fetchSnapshotDataFromDB(Long snapshotTime) {
+        String query = "SELECT S.statsValueList AS statsValueList, M.statsNameList AS statsNameList, S.snapshot_time AS snapshot_time, M.mbeanName AS mbeanName FROM Statistics S, MBeans M WHERE S.snapshot_time=" + snapshotTime;
+        query += " AND S.mbeanId=M.id";
+        ResultSet retval = null;
+        try {
+            if(conn.isClosed()) {
+                openActiveConnection();
+            }
+            Statement stmt = conn.createStatement();
+            retval = stmt.executeQuery(query);
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        }
+        return retval;
+    }
+
+    /**
+     * @return Returns a ResultSet with one column (snapshot_time) sorted in descending order
+     */
+    private ResultSet fetchSnapshotTimesFromDB() {
+        String query = "SELECT DISTINCT snapshot_time FROM Statistics ORDER BY snapshot_time DESC";
+        ResultSet retval = null;
+        try {
+            if(conn.isClosed()) {
+                openActiveConnection();
+            }
+            Statement stmt = conn.createStatement();
+            retval = stmt.executeQuery(query);
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        }
+        return retval;
+    }
+    
+    /**
+     * Opens the global connection to activeDB
+     */
+    private void openActiveConnection() {
+        try {
+            conn = activeDS.getConnection();
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        }
+    }
+    
+    /**
+     * Opens the global connection to archiveDB
+     */
+    private void openArchiveConnection() {
+        try {
+            conn = archiveDS.getConnection();
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        }
+    }
+    
+    /**
+     * Closes the global connection to a DB
+     */
+    private void closeConnection() {
+        if(conn != null) {
+            try {
+                conn.close();
+            } catch(Exception e) {
+                log.error(e.getMessage(), e);
+            }
+        }
+    }
+    
+    /**
+     * @param mbeanName
+     * @param statsName
+     * @param numberOfSnapshots
+     * @param everyNthSnapshot
+     * @return HashMap which maps from a snapshot_time --> value of the mbean.statsName at that time
+     */
+    public TreeMap<Long, Long> getSpecificStatistics(    String mbeanName, 
+                                                                String statsName, 
+                                                                int numberOfSnapshots, 
+                                                                int everyNthSnapshot, 
+                                                                boolean showArchived) {
+        openActiveConnection();
+        TreeMap<Long, Long> stats = new TreeMap<Long, Long>();
+        int nthSnapshot = 0;
+        // attempt to get as many snapshots from the active db as possible
+        try {
+            Statement stmt = conn.createStatement();
+            int mbeanId = getMBeanId(mbeanName);
+            if(mbeanId == -1) {
+                log.error(mbeanName + " does not exist in the database.");
+            } else {
+                String query = "SELECT DISTINCT snapshot_time, statsValueList, statsNameList FROM Statistics, MBeans M WHERE mbeanId=" + mbeanId + " AND mbeanId=M.id ORDER BY snapshot_time DESC";
+                ResultSet rs = stmt.executeQuery(query);
+                // iterate through the table paying attention to those at everyNthSnapshot-th position
+                while(rs.next()) {
+                    // every nth snapshot I save the information into my returning hashmap
+                    if(nthSnapshot % everyNthSnapshot == 0) {
+                        String[] statsValueList = rs.getString(STATSVALUELIST).split(",");
+                        String[] statsNameList = rs.getString(STATSNAMELIST).split(",");
+                        assert(statsValueList.length == statsNameList.length);
+                        Long statsValue = null;
+                        for(int i = 0 ; i < statsNameList.length; i++) {
+                            if(statsNameList[i].equals(statsName)) {
+                                long value = Long.parseLong(statsValueList[i]);
+                                statsValue = new Long(value);
+                            }
+                        }
+                        // exit function after error
+                        if(statsValue == null) {
+                            log.warn("Statistics name '" + statsName + "' does not exist");
+                            return stats;
+                        } else {
+                            stats.put(rs.getLong(SNAPSHOT_TIME), statsValue);
+                            numberOfSnapshots--;
+                        }
+                    }
+                    // update counter
+                    nthSnapshot++;
+                    // enough data, end this thing
+                    if(numberOfSnapshots == 0) {
+                        break;
+                    }
+                }
+            }
+        } catch(Exception e) {
+            log.error(e.getMessage(), e);
+        } finally {
+            closeConnection();
+        }
+
+        nthSnapshot = 0;
+
+        // attempt to get the remaining snapshots requested from the archive DB
+        // iff the showArchive flag is set
+        if(showArchived && numberOfSnapshots != 0) {
+            try {
+                openArchiveConnection();    // connection to the Archive DB
+                Statement stmt = conn.createStatement();
+                int mbeanId = getMBeanId(mbeanName);
+                if(mbeanId == -1) {
+                    log.error(mbeanName + " does not exist in the database.");
+                } else {
+                    String query = "SELECT DISTINCT snapshot_time, statsValueList, statsNameList FROM Statistics, MBeans M WHERE mbeanId=" + mbeanId + " AND mbeanId=M.id ORDER BY snapshot_time DESC";
+                    ResultSet rs = stmt.executeQuery(query);
+                    // iterate through the table paying attention to those at everyNthSnapshot-th position
+                    while(rs.next()) {
+                        // every nth snapshot I save the information into my returning hashmap
+                        if(nthSnapshot % everyNthSnapshot == 0) {
+                            String[] statsValueList = rs.getString(STATSVALUELIST).split(",");
+                            String[] statsNameList = rs.getString(STATSNAMELIST).split(",");
+                            assert(statsValueList.length == statsNameList.length);
+                            Long statsValue = null;
+                            for(int i = 0 ; i < statsNameList.length; i++) {
+                                if(statsNameList[i].equals(statsName)) {
+                                    long value = Long.parseLong(statsValueList[i]);
+                                    statsValue = new Long(value);
+                                }
+                            }
+                            // exit function after error
+                            if(statsValue == null) {
+                                log.warn("Statistics name '" + statsName + "' does not exist");
+                                return stats;
+                            } else {
+                                stats.put(rs.getLong(SNAPSHOT_TIME), statsValue);
+                                numberOfSnapshots--;
+                            }
+                        }
+                        // update counter
+                        nthSnapshot++;
+                        // enough data, end this thing
+                        if(numberOfSnapshots == 0) {
+                            break;
+                        }
+                    }
+                }
+            } catch(Exception e) {
+                log.error(e.getMessage(), e);
+            } finally {
+                closeConnection();
+            }
+        }
+        return stats;
+    }
+    
+    /**
+     * Sets the necessary data sources for this helper to talk to the db
+     * @param activeDS
+     * @param archiveDS
+     */
+    public void setDataSources(DataSource active, DataSource archive) {
+        activeDS = active;
+        archiveDS = archive;
+    }
+}

Modified: geronimo/server/trunk/applications/monitoring/pom.xml
URL: http://svn.apache.org/viewvc/geronimo/server/trunk/applications/monitoring/pom.xml?rev=613704&r1=613703&r2=613704&view=diff
==============================================================================
--- geronimo/server/trunk/applications/monitoring/pom.xml (original)
+++ geronimo/server/trunk/applications/monitoring/pom.xml Sun Jan 20 16:15:47 2008
@@ -7,9 +7,9 @@
     to you under the Apache License, Version 2.0 (the
     "License"); you may not use this file except in compliance
     with the License.  You may obtain a copy of the License at
-    
+
      http://www.apache.org/licenses/LICENSE-2.0
-    
+
     Unless required by applicable law or agreed to in writing,
     software distributed under the License is distributed on an
     "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
@@ -94,8 +94,10 @@
     <modules>
         <module>agent</module>
         <module>agent-ds</module>
+        <module>agent-jar</module>
         <module>agent-ear</module>
         <module>agent-ejb</module>
+	<!--module>agent-jmx</module-->
         <module>agent-sql</module>
         <module>mconsole-ds</module>
         <module>mconsole-ear</module>
@@ -103,7 +105,7 @@
         <module>mconsole-tomcat</module>
         <module>mconsole-war</module>
     </modules>
-    
+
     <build>
         <resources>
             <resource>



Mime
View raw message