KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > sun > enterprise > admin > monitor > registry > spi > StatsMediatorImpl


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

23
24 /* StatsMediatorImpl.java
25  * $Id: StatsMediatorImpl.java,v 1.5 2006/03/14 11:11:54 sankara Exp $
26  * $Revision: 1.5 $
27  * $Date: 2006/03/14 11:11:54 $
28  * Indentation Information:
29  * 0. Please (try to) preserve these settings.
30  * 1. Tabs are preferred over spaces.
31  * 2. In vi/vim -
32  * :set tabstop=4 :set shiftwidth=4 :set softtabstop=4
33  * 3. In S1 Studio -
34  * 1. Tools->Options->Editor Settings->Java Editor->Tab Size = 4
35  * 2. Tools->Options->Indentation Engines->Java Indentation Engine->Expand Tabs to Spaces = False.
36  * 3. Tools->Options->Indentation Engines->Java Indentation Engine->Number of Spaces per Tab = 4.
37  */

38
39 package com.sun.enterprise.admin.monitor.registry.spi;
40
41 import java.lang.reflect.Method JavaDoc;
42 import java.util.Map JavaDoc;
43 import java.util.Iterator JavaDoc;
44 import java.util.HashMap JavaDoc;
45 import java.util.logging.Logger JavaDoc;
46 import java.util.ArrayList JavaDoc;
47 import javax.management.MBeanAttributeInfo JavaDoc;
48
49 import javax.management.j2ee.statistics.Stats JavaDoc;
50 import javax.management.j2ee.statistics.Statistic JavaDoc;
51 import javax.management.j2ee.statistics.BoundedRangeStatistic JavaDoc;
52 import javax.management.j2ee.statistics.CountStatistic JavaDoc;
53 import javax.management.j2ee.statistics.RangeStatistic JavaDoc;
54 import javax.management.j2ee.statistics.TimeStatistic JavaDoc;
55
56 import com.sun.enterprise.admin.monitor.registry.StatsHolder;
57 import com.sun.enterprise.admin.common.constant.AdminConstants;
58 import com.sun.enterprise.util.i18n.StringManager;
59
60 /**
61  * @author <a HREF="mailto:Kedar.Mhaswade@sun.com">Kedar Mhaswade</a>
62  * @since S1AS8.0
63  * @version $Revision: 1.5 $
64  */

65 class StatsMediatorImpl implements StatsMediator {
66     
67     private final Stats JavaDoc delegate;
68     private final Class JavaDoc metaData;
69     private final Map JavaDoc methodMap;
70     private final Map JavaDoc firstParts;
71     private final Map JavaDoc secondParts;
72     private final static Logger JavaDoc logger = Logger.getLogger(AdminConstants.kLoggerName);
73     private final static StringManager sm = StringManager.getManager(StatsMediatorImpl.class);
74     private final String JavaDoc DELIMITER = "-";
75     private final String JavaDoc OLD_DELIMITER = "_";
76     // some JTA specific constants
77
private Map JavaDoc opsMap;
78     private final StatsDescriptionHelper helper = new StatsDescriptionHelper();
79     private final String JavaDoc DESCRIPTION_GETTER = "getDescription";
80     private static final String JavaDoc DOTTED_NAME = "dotted-name";
81
82     public StatsMediatorImpl(Stats JavaDoc delegate, Class JavaDoc metaData) {
83         /* the params are already checked in StatsHolderImpl class and this
84          * class is package-private, hence not checking the params.
85          * Subclasses should take a note of it. */

86         this.delegate = delegate;
87         this.metaData = metaData; //if null, there are no attributes in corresponding mbean
88
this.methodMap = new HashMap JavaDoc();
89         this.firstParts = new HashMap JavaDoc();
90         this.secondParts = new HashMap JavaDoc();
91         reflectedAttributes();
92         // special case handling of JTAStats
93
if (isJtaMetaData())
94             reflectJTAOps();
95     }
96     
97     public Object JavaDoc getAttribute(String JavaDoc name) {
98         if (! methodMap.containsKey(name)) {
99             logger.finer("The name supplied may be an old-styled name, making one more attempt: " + name);
100             name = getHyphenedName(name); //this means the name may be old-styled and we still need to support it.
101
if (! methodMap.containsKey(name)) {
102                 final String JavaDoc msg = sm.getString("smi.no_such_attribute", name);
103                 throw new IllegalArgumentException JavaDoc (msg);
104             }
105         }
106         return ( invokeGetter(name) );
107     }
108     
109     public MBeanAttributeInfo JavaDoc[] getAttributeInfos() {
110         return ( attributes2Info() );
111         
112     }
113     
114     public Object JavaDoc invoke(String JavaDoc method, Object JavaDoc[] params, String JavaDoc[] sign) {
115         // for now this will handle the special case of invoking on
116
// the JTAStats only. Other Stats will be ignored.
117
// the method name has been verified in the StatsHolderMBean
118
logger.fine("Invoking Method: "+method);
119         Object JavaDoc result = null;
120         if(! opsMap.containsKey(method)) {
121             final String JavaDoc msg = sm.getString("smi.no_such_method", method);
122             throw new IllegalArgumentException JavaDoc(msg);
123         }
124         else
125         {
126             Method JavaDoc m = (Method JavaDoc)opsMap.get(method);
127             try {
128                 result = m.invoke(this.delegate, params);
129             } catch(Exception JavaDoc e) {
130                 logger.info(e.getMessage());
131             }
132         }
133         return result;
134     }
135     
136     private void reflectedAttributes() {
137         if (metaData == null)
138             return; //this means that this instance does not have any stats
139
/* Note that only method names come from the class (metaData) and
140          * actual Method object should come from the Stats Object to which the
141          * getters will delegate. */

142         final Method JavaDoc[] methods = metaData.getMethods();
143         for (int i = 0; i < methods.length ; i++) {
144             final String JavaDoc method = methods[i].getName();
145             if (isStatsInterfaceMethod(method))
146                 continue; //ignore the methods from the super interface javax.management.j2ee.statistics.Stats
147
final int index = method.indexOf("get");
148             // a non-getXXX method name should not be processed any further
149
// needed to support the ops in the JTAStats
150
if(index != -1) {
151                 final String JavaDoc baseAttrName = method.substring(index + 3);
152                 final String JavaDoc[] attrSubs = getAttributeSubs(methods[i]);
153                 final Method JavaDoc actualMethod = getMethodFromDelegate(method);
154                 addMapping(baseAttrName, attrSubs, actualMethod);
155             }
156         }
157     }
158     
159     private void reflectJTAOps() {
160         opsMap = new HashMap JavaDoc();
161         final Method JavaDoc[] methods = metaData.getMethods();
162         for(int i = 0; i < methods.length ; i++) {
163             String JavaDoc methodName = methods[i].getName();
164             if((StatsHolderMBeanImpl.JTA_FREEZE.equals(methodName)) ||
165                (StatsHolderMBeanImpl.JTA_UNFREEZE.equals(methodName)) ||
166                (StatsHolderMBeanImpl.JTA_ACTIVE_TRANSACTIONS.equals(methodName)) ||
167                (StatsHolderMBeanImpl.JTA_ROLLBACK.equals(methodName))) {
168                    
169                 opsMap.put(methodName, methods[i]);
170             }
171         }
172     }
173     
174     /**
175      * Returns true if and only if the metaData is non null and is an instance
176      * of JTAStats interface.
177      */

178     private boolean isJtaMetaData() {
179         boolean jta = false;
180         if (metaData != null) {
181             if (com.sun.enterprise.admin.monitor.stats.JTAStats.class.getName().equals(metaData.getName()))
182                 jta = true;
183         }
184         return ( jta );
185     }
186     private boolean isStatsInterfaceMethod(String JavaDoc name) {
187         final Method JavaDoc[] methods = javax.management.j2ee.statistics.Stats JavaDoc.class.getMethods();
188         boolean isInterfaceMethod = false;
189         for (int i = 0 ; i < methods.length ; i++) {
190             if (methods[i].getName().equals(name)) {
191                 isInterfaceMethod = true;
192                 break;
193             }
194         }
195         return ( isInterfaceMethod );
196     }
197     private Method JavaDoc getMethodFromDelegate(String JavaDoc methodName) {
198         final Method JavaDoc[] instanceMethods = delegate.getClass().getMethods();
199         Method JavaDoc m = null;
200         boolean matched = false;
201         for (int i = 0 ; i < instanceMethods.length ; i++) {
202             m = instanceMethods[i];
203             if (methodName.equals(m.getName())) {
204                 matched = true;
205                 break;
206             }
207         }
208         assert (matched != false) : "The Stats object: " + delegate.getClass().getName() + " does not implement declared method: " + methodName;
209         return ( m );
210     }
211     private String JavaDoc[] getAttributeSubs(Method JavaDoc m) {
212         final Class JavaDoc c = m.getReturnType();
213         assert (javax.management.j2ee.statistics.Statistic JavaDoc.class.isAssignableFrom(c)) : "The method does not return a Statistic: " + m.getName();
214         //assert (c.isInterface()) : "Has to be an interface: " + c.getName();
215
final Method JavaDoc[] rets = c.getMethods();
216         final String JavaDoc[] subs = new String JavaDoc[rets.length];
217         for (int i = 0 ; i < rets.length ; i++) {
218             final Method JavaDoc am = rets[i];
219             final String JavaDoc name = am.getName();
220             if (name.startsWith("get")) {
221                 subs[i] = name.substring(3); //String length of "get"
222
logger.fine("return type = " + subs[i]);
223             }
224         }
225         return ( subs );
226     }
227     private void addMapping(String JavaDoc first, String JavaDoc[] lasts, Method JavaDoc getter) {
228         for (int i = 0 ; i < lasts.length ; i++) {
229             String JavaDoc lc1 = null;
230             if (first != null) {
231                 lc1 = first.toLowerCase();
232             }
233             if ( lasts[i] != null) {
234                 final String JavaDoc lc2 = lasts[i].toLowerCase();
235                 final String JavaDoc full = new StringBuffer JavaDoc(lc1).append(DELIMITER).append(lc2).toString();
236                 methodMap.put(full, getter);
237                 firstParts.put(lc1, first);
238                 secondParts.put(lc2, lasts[i]);
239                 logger.finer("Method: " + getter.getName() + " added for full attribute: " + full);
240             }
241         }
242     }
243     private Object JavaDoc invokeGetter(String JavaDoc ab) {
244         //it is already checked if this is a valid attribute;
245
String JavaDoc first = ab.substring(0, ab.indexOf(DELIMITER));
246         first = (String JavaDoc)firstParts.get(first);
247         final String JavaDoc fName = "get" + first;
248         String JavaDoc last = ab.substring(ab.indexOf(DELIMITER) + 1);
249         last = (String JavaDoc)secondParts.get(last);
250         final String JavaDoc lName = "get" + last;
251         if(lName.equalsIgnoreCase(DESCRIPTION_GETTER))
252             return ((Object JavaDoc)getDescription(first));
253     
254         Method JavaDoc lastMethod = null;
255         try {
256             final Method JavaDoc firstMethod = (Method JavaDoc)methodMap.get(ab);
257             final Object JavaDoc firstResult = firstMethod.invoke(delegate);
258             lastMethod = firstResult.getClass().getMethod(lName);
259             final Object JavaDoc value = lastMethod.invoke(firstResult);
260             logger.finer("Got value for: " + ab + " as: " + value + " class = " + value.getClass().getName());
261             return ( value );
262         }
263         catch(Exception JavaDoc e) {
264             logger.throwing(StatsMediatorImpl.class.getName(), "invokeGetter", e);
265             throw new RuntimeException JavaDoc (e);
266         }
267     }
268     
269     private MBeanAttributeInfo JavaDoc[] attributes2Info() {
270         //go through all the attrs and build the MBeanAttributeInfo[]
271
final Iterator JavaDoc it = methodMap.keySet().iterator();
272         final ArrayList JavaDoc attrInfo = new ArrayList JavaDoc();
273
274         int i = 0;
275         while (it.hasNext()) {
276             final String JavaDoc name = (String JavaDoc) it.next();
277             final String JavaDoc type = getType(name);
278             final String JavaDoc desc = getDescription(name);
279             final boolean isReadable = getReadable(name);
280             final boolean isWritable = false; //change for JTA
281
final boolean isIs = false;
282             attrInfo.add(new MBeanAttributeInfo JavaDoc(name, type, desc, isReadable, isWritable, isIs));
283             logger.finer("Added the attribute to MBeanAttributeInfo: " + name);
284         }
285         // also add the dotted name as an attribute of the MBean
286
MBeanAttributeInfo JavaDoc dottedNameInfo = new MBeanAttributeInfo JavaDoc(StatsHolderMBeanImpl.DOTTED_NAME,
287                                                                    getType(DOTTED_NAME),
288                                                                    getDescription(DOTTED_NAME),
289                                                                    true,
290                                                                    false,
291                                                                    false);
292         attrInfo.add(dottedNameInfo);
293         final MBeanAttributeInfo JavaDoc[] ais = new MBeanAttributeInfo JavaDoc[attrInfo.size()];
294         logger.finer("No of attrs = " + attrInfo.size());
295         return (MBeanAttributeInfo JavaDoc[])attrInfo.toArray(ais);
296     }
297     
298     private String JavaDoc getDescription(String JavaDoc name) {
299         return helper.getDescription(name);
300     }
301     
302     private String JavaDoc getType(String JavaDoc name) {
303         return ( "java.lang.String" ); //will change later
304
}
305     
306     private boolean getReadable(String JavaDoc name) {
307         return ( true ); // will change later
308
}
309     
310     /** Returns a name with hyphens and lower case characters.
311      * This method is there only to support the J2EE 1.4 SDK release which
312      * supported such names as HeapSize_Current. This method will return a String
313      * that is a modified form of the passed String. The call to this method
314      * occurs only when the given attribute is not found in the method map of
315      * this class.
316      */

317     private String JavaDoc getHyphenedName(final String JavaDoc name) {
318         return ( name.toLowerCase().replace(OLD_DELIMITER.charAt(0), DELIMITER.charAt(0)) );
319     }
320 }
321
Popular Tags