View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package org.apache.mina.integration.jmx;
18  
19  import java.beans.IntrospectionException;
20  import java.beans.Introspector;
21  import java.beans.PropertyDescriptor;
22  import java.beans.PropertyEditor;
23  import java.lang.reflect.InvocationTargetException;
24  import java.lang.reflect.Method;
25  import java.net.SocketAddress;
26  import java.util.ArrayList;
27  import java.util.Collection;
28  import java.util.Date;
29  import java.util.HashMap;
30  import java.util.Iterator;
31  import java.util.LinkedHashMap;
32  import java.util.LinkedHashSet;
33  import java.util.List;
34  import java.util.Map;
35  import java.util.Set;
36  import java.util.concurrent.ConcurrentHashMap;
37  import java.util.concurrent.ThreadPoolExecutor;
38  
39  import javax.management.Attribute;
40  import javax.management.AttributeChangeNotification;
41  import javax.management.AttributeList;
42  import javax.management.AttributeNotFoundException;
43  import javax.management.InstanceNotFoundException;
44  import javax.management.ListenerNotFoundException;
45  import javax.management.MBeanException;
46  import javax.management.MBeanInfo;
47  import javax.management.MBeanNotificationInfo;
48  import javax.management.MBeanParameterInfo;
49  import javax.management.MBeanRegistration;
50  import javax.management.MBeanServer;
51  import javax.management.Notification;
52  import javax.management.NotificationFilter;
53  import javax.management.NotificationListener;
54  import javax.management.ObjectName;
55  import javax.management.ReflectionException;
56  import javax.management.RuntimeOperationsException;
57  import javax.management.modelmbean.InvalidTargetObjectTypeException;
58  import javax.management.modelmbean.ModelMBean;
59  import javax.management.modelmbean.ModelMBeanAttributeInfo;
60  import javax.management.modelmbean.ModelMBeanConstructorInfo;
61  import javax.management.modelmbean.ModelMBeanInfo;
62  import javax.management.modelmbean.ModelMBeanInfoSupport;
63  import javax.management.modelmbean.ModelMBeanNotificationInfo;
64  import javax.management.modelmbean.ModelMBeanOperationInfo;
65  
66  import ognl.ExpressionSyntaxException;
67  import ognl.InappropriateExpressionException;
68  import ognl.NoSuchPropertyException;
69  import ognl.Ognl;
70  import ognl.OgnlContext;
71  import ognl.OgnlException;
72  import ognl.OgnlRuntime;
73  import ognl.TypeConverter;
74  
75  import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
76  import org.apache.mina.core.filterchain.IoFilter;
77  import org.apache.mina.core.filterchain.IoFilterChain;
78  import org.apache.mina.core.filterchain.IoFilterChainBuilder;
79  import org.apache.mina.core.service.IoAcceptor;
80  import org.apache.mina.core.service.IoHandler;
81  import org.apache.mina.core.service.IoService;
82  import org.apache.mina.core.service.TransportMetadata;
83  import org.apache.mina.core.session.IoSession;
84  import org.apache.mina.core.session.IoSessionDataStructureFactory;
85  import org.apache.mina.filter.executor.ExecutorFilter;
86  import org.apache.mina.integration.beans.CollectionEditor;
87  import org.apache.mina.integration.beans.ListEditor;
88  import org.apache.mina.integration.beans.MapEditor;
89  import org.apache.mina.integration.beans.PropertyEditorFactory;
90  import org.apache.mina.integration.beans.SetEditor;
91  import org.apache.mina.integration.ognl.IoFilterPropertyAccessor;
92  import org.apache.mina.integration.ognl.IoServicePropertyAccessor;
93  import org.apache.mina.integration.ognl.IoSessionPropertyAccessor;
94  import org.apache.mina.integration.ognl.PropertyTypeConverter;
95  import org.slf4j.Logger;
96  import org.slf4j.LoggerFactory;
97  
98  /**
99   * A {@link ModelMBean} wrapper implementation for a POJO.
100  *
101  * @author <a href="http://mina.apache.org">Apache MINA Project</a>
102  *
103  * @param <T> the type of the managed object
104  */
105 public class ObjectMBean<T> implements ModelMBean, MBeanRegistration {
106 
107     private static final Map<ObjectName, Object> sources = new ConcurrentHashMap<ObjectName, Object>();
108 
109     /**
110      * Get the monitored object
111      * 
112      * @param oname The object name
113      * @return The monitored object
114      */
115     public static Object getSource(ObjectName oname) {
116         return sources.get(oname);
117     }
118 
119     static {
120         OgnlRuntime.setPropertyAccessor(IoService.class, new IoServicePropertyAccessor());
121         OgnlRuntime.setPropertyAccessor(IoSession.class, new IoSessionPropertyAccessor());
122         OgnlRuntime.setPropertyAccessor(IoFilter.class, new IoFilterPropertyAccessor());
123     }
124 
125     protected final static Logger LOGGER = LoggerFactory.getLogger(ObjectMBean.class);
126 
127     private final T source;
128 
129     private final TransportMetadata transportMetadata;
130 
131     private final MBeanInfo info;
132 
133     private final Map<String, PropertyDescriptor> propertyDescriptors = new HashMap<String, PropertyDescriptor>();
134 
135     private final TypeConverter typeConverter = new OgnlTypeConverter();
136 
137     private volatile MBeanServer server;
138 
139     private volatile ObjectName name;
140 
141     /**
142      * Creates a new instance with the specified POJO.
143      * 
144      * @param source The original POJO
145      */
146     public ObjectMBean(T source) {
147         if (source == null) {
148             throw new IllegalArgumentException("source");
149         }
150 
151         this.source = source;
152 
153         if (source instanceof IoService) {
154             transportMetadata = ((IoService) source).getTransportMetadata();
155         } else if (source instanceof IoSession) {
156             transportMetadata = ((IoSession) source).getTransportMetadata();
157         } else {
158             transportMetadata = null;
159         }
160 
161         this.info = createModelMBeanInfo(source);
162     }
163 
164     public final Object getAttribute(String fqan) throws AttributeNotFoundException, MBeanException,
165     ReflectionException {
166         try {
167             return convertValue(source.getClass(), fqan, getAttribute0(fqan), false);
168         } catch (AttributeNotFoundException e) {
169             // Do nothing
170         } catch (Exception e) {
171             throwMBeanException(e);
172         }
173 
174         // Check if the attribute exist, if not throw an exception
175         PropertyDescriptor pdesc = propertyDescriptors.get(fqan);
176         if (pdesc == null) {
177             throwMBeanException(new IllegalArgumentException("Unknown attribute: " + fqan));
178         }
179 
180         try {
181 
182             Object parent = getParent(fqan);
183             boolean writable = isWritable(source.getClass(), pdesc);
184 
185             return convertValue(parent.getClass(), getLeafAttributeName(fqan),
186                     getAttribute(source, fqan, pdesc.getPropertyType()), writable);
187         } catch (Exception e) {
188             throwMBeanException(e);
189         }
190 
191         throw new IllegalStateException();
192     }
193 
194     public final void setAttribute(Attribute attribute) throws AttributeNotFoundException, MBeanException,
195     ReflectionException {
196         String aname = attribute.getName();
197         Object avalue = attribute.getValue();
198 
199         try {
200             setAttribute0(aname, avalue);
201         } catch (AttributeNotFoundException e) {
202             // Do nothing
203         } catch (Exception e) {
204             throwMBeanException(e);
205         }
206 
207         PropertyDescriptor pdesc = propertyDescriptors.get(aname);
208         if (pdesc == null) {
209             throwMBeanException(new IllegalArgumentException("Unknown attribute: " + aname));
210         }
211 
212         try {
213             PropertyEditor e = getPropertyEditor(getParent(aname).getClass(), pdesc.getName(), pdesc.getPropertyType());
214             e.setAsText((String) avalue);
215             OgnlContext ctx = (OgnlContext) Ognl.createDefaultContext(source);
216             ctx.setTypeConverter(typeConverter);
217             Ognl.setValue(aname, ctx, source, e.getValue());
218         } catch (Exception e) {
219             throwMBeanException(e);
220         }
221     }
222 
223     public final Object invoke(String name, Object params[], String signature[]) throws MBeanException,
224     ReflectionException {
225 
226         // Handle synthetic operations first.
227         if (name.equals("unregisterMBean")) {
228             try {
229                 server.unregisterMBean(this.name);
230                 return null;
231             } catch (InstanceNotFoundException e) {
232                 throwMBeanException(e);
233             }
234         }
235 
236         try {
237             return convertValue(null, null, invoke0(name, params, signature), false);
238         } catch (NoSuchMethodException e) {
239             // Do nothing
240         } catch (Exception e) {
241             throwMBeanException(e);
242         }
243 
244         // And then try reflection.
245         Class<?>[] paramTypes = new Class[signature.length];
246         for (int i = 0; i < paramTypes.length; i++) {
247             try {
248                 paramTypes[i] = getAttributeClass(signature[i]);
249             } catch (ClassNotFoundException e) {
250                 throwMBeanException(e);
251             }
252 
253             PropertyEditor e = getPropertyEditor(source.getClass(), "p" + i, paramTypes[i]);
254             if (e == null) {
255                 throwMBeanException(new RuntimeException("Conversion failure: " + params[i]));
256             }
257 
258             e.setValue(params[i]);
259             params[i] = e.getAsText();
260         }
261 
262         try {
263             // Find the right method.
264             for (Method m : source.getClass().getMethods()) {
265                 if (!m.getName().equalsIgnoreCase(name)) {
266                     continue;
267                 }
268                 Class<?>[] methodParamTypes = m.getParameterTypes();
269                 if (methodParamTypes.length != params.length) {
270                     continue;
271                 }
272 
273                 Object[] convertedParams = new Object[params.length];
274                 for (int i = 0; i < params.length; i++) {
275                     if (Iterable.class.isAssignableFrom(methodParamTypes[i])) {
276                         // Generics are not supported.
277                         convertedParams = null;
278                         break;
279                     }
280                     PropertyEditor e = getPropertyEditor(source.getClass(), "p" + i, methodParamTypes[i]);
281                     if (e == null) {
282                         convertedParams = null;
283                         break;
284                     }
285 
286                     e.setAsText((String) params[i]);
287                     convertedParams[i] = e.getValue();
288                 }
289                 if (convertedParams == null) {
290                     continue;
291                 }
292 
293                 return convertValue(m.getReturnType(), "returnValue", m.invoke(source, convertedParams), false);
294             }
295 
296             // No methods matched.
297             throw new IllegalArgumentException("Failed to find a matching operation: " + name);
298         } catch (Exception e) {
299             throwMBeanException(e);
300         }
301 
302         throw new IllegalStateException();
303     }
304 
305     /**
306      * @return The monitored object
307      */
308     public final T getSource() {
309         return source;
310     }
311 
312     /**
313      * @return The MBrean server
314      */
315     public final MBeanServer getServer() {
316         return server;
317     }
318 
319     /**
320      * @return The monitored object name
321      */
322     public final ObjectName getName() {
323         return name;
324     }
325 
326     public final MBeanInfo getMBeanInfo() {
327         return info;
328     }
329 
330     public final AttributeList getAttributes(String names[]) {
331         AttributeList answer = new AttributeList();
332         for (int i = 0; i < names.length; i++) {
333             try {
334                 answer.add(new Attribute(names[i], getAttribute(names[i])));
335             } catch (Exception e) {
336                 // Ignore.
337             }
338         }
339         return answer;
340     }
341 
342     public final AttributeList setAttributes(AttributeList attributes) {
343         // Prepare and return our response, eating all exceptions
344         String names[] = new String[attributes.size()];
345         int n = 0;
346         Iterator<Object> items = attributes.iterator();
347         while (items.hasNext()) {
348             Attribute item = (Attribute) items.next();
349             names[n++] = item.getName();
350             try {
351                 setAttribute(item);
352             } catch (Exception e) {
353                 // Ignore all exceptions
354             }
355         }
356 
357         return getAttributes(names);
358     }
359 
360     public final void setManagedResource(Object resource, String type) throws InstanceNotFoundException,
361     InvalidTargetObjectTypeException, MBeanException {
362         throw new RuntimeOperationsException(new UnsupportedOperationException());
363 
364     }
365 
366     public final void setModelMBeanInfo(ModelMBeanInfo info) throws MBeanException {
367         throw new RuntimeOperationsException(new UnsupportedOperationException());
368     }
369 
370     @Override
371     public final String toString() {
372         return (source == null ? "" : source.toString());
373     }
374 
375     public void addAttributeChangeNotificationListener(NotificationListener listener, String name, Object handback) {
376         // Do nothing
377     }
378 
379     public void removeAttributeChangeNotificationListener(NotificationListener listener, String name)
380             throws ListenerNotFoundException {
381         // Do nothing
382     }
383 
384     public void sendAttributeChangeNotification(AttributeChangeNotification notification) throws MBeanException {
385         throw new RuntimeOperationsException(new UnsupportedOperationException());
386     }
387 
388     public void sendAttributeChangeNotification(Attribute oldValue, Attribute newValue) throws MBeanException {
389         throw new RuntimeOperationsException(new UnsupportedOperationException());
390     }
391 
392     public void sendNotification(Notification notification) throws MBeanException {
393         throw new RuntimeOperationsException(new UnsupportedOperationException());
394     }
395 
396     public void sendNotification(String message) throws MBeanException {
397         throw new RuntimeOperationsException(new UnsupportedOperationException());
398 
399     }
400 
401     public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback)
402             throws IllegalArgumentException {
403         // Do nothing
404     }
405 
406     public MBeanNotificationInfo[] getNotificationInfo() {
407         return new MBeanNotificationInfo[0];
408     }
409 
410     public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
411         // Do nothing
412     }
413 
414     public void load() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException {
415         throw new RuntimeOperationsException(new UnsupportedOperationException());
416     }
417 
418     public void store() throws InstanceNotFoundException, MBeanException, RuntimeOperationsException {
419         throw new RuntimeOperationsException(new UnsupportedOperationException());
420     }
421 
422     public final ObjectName preRegister(MBeanServer server, ObjectName name) throws Exception {
423         this.server = server;
424         this.name = name;
425         return name;
426     }
427 
428     public final void postRegister(Boolean registrationDone) {
429         if (registrationDone) {
430             sources.put(name, source);
431         }
432     }
433 
434     public final void preDeregister() throws Exception {
435         // Do nothing
436     }
437 
438     public final void postDeregister() {
439         sources.remove(name);
440         this.server = null;
441         this.name = null;
442     }
443 
444     private MBeanInfo createModelMBeanInfo(T source) {
445         String className = source.getClass().getName();
446         String description = "";
447 
448         ModelMBeanConstructorInfo[] constructors = new ModelMBeanConstructorInfo[0];
449         ModelMBeanNotificationInfo[] notifications = new ModelMBeanNotificationInfo[0];
450 
451         List<ModelMBeanAttributeInfo> attributes = new ArrayList<ModelMBeanAttributeInfo>();
452         List<ModelMBeanOperationInfo> operations = new ArrayList<ModelMBeanOperationInfo>();
453 
454         addAttributes(attributes, source);
455         addExtraAttributes(attributes);
456 
457         addOperations(operations, source);
458         addExtraOperations(operations);
459         operations.add(new ModelMBeanOperationInfo("unregisterMBean", "unregisterMBean", new MBeanParameterInfo[0],
460                 void.class.getName(), ModelMBeanOperationInfo.ACTION));
461 
462         return new ModelMBeanInfoSupport(className, description,
463                 attributes.toArray(new ModelMBeanAttributeInfo[attributes.size()]), constructors,
464                 operations.toArray(new ModelMBeanOperationInfo[operations.size()]), notifications);
465     }
466 
467     private void addAttributes(List<ModelMBeanAttributeInfo> attributes, Object object) {
468         addAttributes(attributes, object, object.getClass(), "");
469     }
470 
471     private void addAttributes(List<ModelMBeanAttributeInfo> attributes, Object object, Class<?> type, String prefix) {
472 
473         PropertyDescriptor[] pdescs;
474         try {
475             pdescs = Introspector.getBeanInfo(type).getPropertyDescriptors();
476         } catch (IntrospectionException e) {
477             return;
478         }
479 
480         for (PropertyDescriptor pdesc : pdescs) {
481             // Ignore a write-only property.
482             if (pdesc.getReadMethod() == null) {
483                 continue;
484             }
485 
486             // Ignore unmanageable property.
487             String attrName = pdesc.getName();
488             Class<?> attrType = pdesc.getPropertyType();
489             if (attrName.equals("class")) {
490                 continue;
491             }
492             if (!isReadable(type, attrName)) {
493                 continue;
494             }
495 
496             // Expand if possible.
497             if (isExpandable(type, attrName)) {
498                 expandAttribute(attributes, object, prefix, pdesc);
499                 continue;
500             }
501 
502             // Ordinary property.
503             String fqan = prefix + attrName;
504             boolean writable = isWritable(type, pdesc);
505             attributes.add(new ModelMBeanAttributeInfo(fqan, convertType(object.getClass(), attrName, attrType,
506                     writable).getName(), pdesc.getShortDescription(), true, writable, false));
507 
508             propertyDescriptors.put(fqan, pdesc);
509         }
510     }
511 
512     private boolean isWritable(Class<?> type, PropertyDescriptor pdesc) {
513         if (type == null) {
514             throw new IllegalArgumentException("type");
515         }
516         if (pdesc == null) {
517             return false;
518         }
519         String attrName = pdesc.getName();
520         Class<?> attrType = pdesc.getPropertyType();
521         boolean writable = (pdesc.getWriteMethod() != null) || isWritable(type, attrName);
522         if (getPropertyEditor(type, attrName, attrType) == null) {
523             writable = false;
524         }
525         return writable;
526     }
527 
528     private void expandAttribute(List<ModelMBeanAttributeInfo> attributes, Object object, String prefix,
529             PropertyDescriptor pdesc) {
530         Object property;
531         String attrName = pdesc.getName();
532         try {
533             property = getAttribute(object, attrName, pdesc.getPropertyType());
534         } catch (Exception e) {
535             LOGGER.debug("Unexpected exception.", e);
536             return;
537         }
538 
539         if (property == null) {
540             return;
541         }
542 
543         addAttributes(attributes, property, property.getClass(), prefix + attrName + '.');
544     }
545 
546     private void addOperations(List<ModelMBeanOperationInfo> operations, Object object) {
547 
548         for (Method m : object.getClass().getMethods()) {
549             String mname = m.getName();
550 
551             // Ignore getters and setters.
552             if (mname.startsWith("is") || mname.startsWith("get") || mname.startsWith("set")) {
553                 continue;
554             }
555 
556             // Ignore Object methods.
557             if (mname.matches("(wait|notify|notifyAll|toString|equals|compareTo|hashCode|clone)")) {
558                 continue;
559             }
560 
561             // Ignore other user-defined non-operations.
562             if (!isOperation(mname, m.getParameterTypes())) {
563                 continue;
564             }
565 
566             List<MBeanParameterInfo> signature = new ArrayList<MBeanParameterInfo>();
567             int i = 1;
568             for (Class<?> paramType : m.getParameterTypes()) {
569                 String paramName = "p" + (i++);
570                 if (getPropertyEditor(source.getClass(), paramName, paramType) == null) {
571                     continue;
572                 }
573                 signature.add(new MBeanParameterInfo(paramName, convertType(null, null, paramType, true).getName(),
574                         paramName));
575             }
576 
577             Class<?> returnType = convertType(null, null, m.getReturnType(), false);
578             operations.add(new ModelMBeanOperationInfo(m.getName(), m.getName(), signature
579                     .toArray(new MBeanParameterInfo[signature.size()]), returnType.getName(),
580                     ModelMBeanOperationInfo.ACTION));
581         }
582     }
583 
584     private Object getParent(String fqan) throws OgnlException {
585         Object parent;
586         int dotIndex = fqan.lastIndexOf('.');
587         if (dotIndex < 0) {
588             parent = source;
589         } else {
590             parent = getAttribute(source, fqan.substring(0, dotIndex), null);
591         }
592         return parent;
593     }
594 
595     private String getLeafAttributeName(String fqan) {
596         int dotIndex = fqan.lastIndexOf('.');
597         if (dotIndex < 0) {
598             return fqan;
599         }
600         return fqan.substring(dotIndex + 1);
601     }
602 
603     private Class<?> getAttributeClass(String signature) throws ClassNotFoundException {
604         if (signature.equals(Boolean.TYPE.getName())) {
605             return Boolean.TYPE;
606         }
607         if (signature.equals(Byte.TYPE.getName())) {
608             return Byte.TYPE;
609         }
610         if (signature.equals(Character.TYPE.getName())) {
611             return Character.TYPE;
612         }
613         if (signature.equals(Double.TYPE.getName())) {
614             return Double.TYPE;
615         }
616         if (signature.equals(Float.TYPE.getName())) {
617             return Float.TYPE;
618         }
619         if (signature.equals(Integer.TYPE.getName())) {
620             return Integer.TYPE;
621         }
622         if (signature.equals(Long.TYPE.getName())) {
623             return Long.TYPE;
624         }
625         if (signature.equals(Short.TYPE.getName())) {
626             return Short.TYPE;
627         }
628 
629         try {
630             ClassLoader cl = Thread.currentThread().getContextClassLoader();
631             if (cl != null) {
632                 return cl.loadClass(signature);
633             }
634         } catch (ClassNotFoundException e) {
635             // Do nothing
636         }
637 
638         return Class.forName(signature);
639     }
640 
641     private Object getAttribute(Object object, String fqan, Class<?> attrType) throws OgnlException {
642         Object property;
643         OgnlContext ctx = (OgnlContext) Ognl.createDefaultContext(object);
644         ctx.setTypeConverter(new OgnlTypeConverter());
645         if (attrType == null) {
646             property = Ognl.getValue(fqan, ctx, object);
647         } else {
648             property = Ognl.getValue(fqan, ctx, object, attrType);
649         }
650         return property;
651     }
652 
653     private Class<?> convertType(Class<?> type, String attrName, Class<?> attrType, boolean writable) {
654         if ((attrName != null) && ((attrType == Long.class) || (attrType == long.class))) {
655             if (attrName.endsWith("Time") && (attrName.indexOf("Total") < 0) && (attrName.indexOf("Min") < 0)
656                     && (attrName.indexOf("Max") < 0) && (attrName.indexOf("Avg") < 0)
657                     && (attrName.indexOf("Average") < 0) && !propertyDescriptors.containsKey(attrName + "InMillis")) {
658                 return Date.class;
659             }
660         }
661 
662         if (IoFilterChain.class.isAssignableFrom(attrType)) {
663             return Map.class;
664         }
665 
666         if (IoFilterChainBuilder.class.isAssignableFrom(attrType)) {
667             return Map.class;
668         }
669 
670         if (!writable) {
671             if (Collection.class.isAssignableFrom(attrType) || Map.class.isAssignableFrom(attrType)) {
672                 if (List.class.isAssignableFrom(attrType)) {
673                     return List.class;
674                 }
675                 if (Set.class.isAssignableFrom(attrType)) {
676                     return Set.class;
677                 }
678                 if (Map.class.isAssignableFrom(attrType)) {
679                     return Map.class;
680                 }
681                 return Collection.class;
682             }
683 
684             if (attrType.isPrimitive() || Date.class.isAssignableFrom(attrType)
685                     || Boolean.class.isAssignableFrom(attrType) || Character.class.isAssignableFrom(attrType)
686                     || Number.class.isAssignableFrom(attrType)) {
687                 if ((attrName == null) || !attrName.endsWith("InMillis")
688                         || !propertyDescriptors.containsKey(attrName.substring(0, attrName.length() - 8))) {
689                     return attrType;
690                 }
691             }
692         }
693 
694         return String.class;
695     }
696 
697     private Object convertValue(Class<?> type, String attrName, Object v, boolean writable) {
698         if (v == null) {
699             return null;
700         }
701 
702         if ((attrName != null) && (v instanceof Long)) {
703             if (attrName.endsWith("Time") && (attrName.indexOf("Total") < 0) && (attrName.indexOf("Min") < 0)
704                     && (attrName.indexOf("Max") < 0) && (attrName.indexOf("Avg") < 0)
705                     && (attrName.indexOf("Average") < 0) && !propertyDescriptors.containsKey(attrName + "InMillis")) {
706                 long time = (Long) v;
707                 if (time <= 0) {
708                     return null;
709                 }
710 
711                 return new Date((Long) v);
712             }
713         }
714 
715         if ((v instanceof IoSessionDataStructureFactory) || (v instanceof IoHandler)) {
716             return v.getClass().getName();
717         }
718 
719         if (v instanceof IoFilterChainBuilder) {
720             Map<String, String> filterMapping = new LinkedHashMap<String, String>();
721             if (v instanceof DefaultIoFilterChainBuilder) {
722                 for (IoFilterChain.Entry e : ((DefaultIoFilterChainBuilder) v).getAll()) {
723                     filterMapping.put(e.getName(), e.getFilter().getClass().getName());
724                 }
725             } else {
726                 filterMapping.put("Unknown builder type", v.getClass().getName());
727             }
728             return filterMapping;
729         }
730 
731         if (v instanceof IoFilterChain) {
732             Map<String, String> filterMapping = new LinkedHashMap<String, String>();
733             for (IoFilterChain.Entry e : ((IoFilterChain) v).getAll()) {
734                 filterMapping.put(e.getName(), e.getFilter().getClass().getName());
735             }
736             return filterMapping;
737         }
738 
739         if (!writable) {
740             if ((v instanceof Collection) || (v instanceof Map)) {
741                 if (v instanceof List) {
742                     return convertCollection(v, new ArrayList<Object>());
743                 }
744                 if (v instanceof Set) {
745                     return convertCollection(v, new LinkedHashSet<Object>());
746                 }
747                 if (v instanceof Map) {
748                     return convertCollection(v, new LinkedHashMap<Object, Object>());
749                 }
750                 return convertCollection(v, new ArrayList<Object>());
751             }
752 
753             if ((v instanceof Date) || (v instanceof Boolean) || (v instanceof Character) || (v instanceof Number)) {
754                 if ((attrName == null) || !attrName.endsWith("InMillis")
755                         || !propertyDescriptors.containsKey(attrName.substring(0, attrName.length() - 8))) {
756                     return v;
757                 }
758             }
759         }
760 
761         PropertyEditor editor = getPropertyEditor(type, attrName, v.getClass());
762         if (editor != null) {
763             editor.setValue(v);
764             return editor.getAsText();
765         }
766 
767         return v.toString();
768     }
769 
770     private Object convertCollection(Object src, Collection<Object> dst) {
771         Collection<?> srcCol = (Collection<?>) src;
772         for (Object e : srcCol) {
773             Object convertedValue = convertValue(dst.getClass(), "element", e, false);
774             if ((e != null) && (convertedValue == null)) {
775                 convertedValue = e.toString();
776             }
777             dst.add(convertedValue);
778         }
779         return dst;
780     }
781 
782     private Object convertCollection(Object src, Map<Object, Object> dst) {
783         Map<?, ?> srcCol = (Map<?, ?>) src;
784         for (Map.Entry<?, ?> e : srcCol.entrySet()) {
785             Object convertedKey = convertValue(dst.getClass(), "key", e.getKey(), false);
786             Object convertedValue = convertValue(dst.getClass(), "value", e.getValue(), false);
787             if ((e.getKey() != null) && (convertedKey == null)) {
788                 convertedKey = e.getKey().toString();
789             }
790             if ((e.getValue() != null) && (convertedValue == null)) {
791                 convertedKey = e.getValue().toString();
792             }
793             dst.put(convertedKey, convertedValue);
794         }
795         return dst;
796     }
797 
798     private void throwMBeanException(Throwable e) throws MBeanException {
799         if (e instanceof OgnlException) {
800             OgnlException ognle = (OgnlException) e;
801 
802             if (ognle.getReason() != null) {
803                 throwMBeanException(ognle.getReason());
804             } else {
805                 String message = ognle.getMessage();
806 
807                 if (e instanceof NoSuchPropertyException) {
808                     message = "No such property: " + message;
809                 } else if (e instanceof ExpressionSyntaxException) {
810                     message = "Illegal expression syntax: " + message;
811                 } else if (e instanceof InappropriateExpressionException) {
812                     message = "Inappropriate expression: " + message;
813                 }
814 
815                 e = new IllegalArgumentException(message);
816                 e.setStackTrace(ognle.getStackTrace());
817             }
818         }
819         if (e instanceof InvocationTargetException) {
820             throwMBeanException(e.getCause());
821         }
822 
823         LOGGER.warn("Unexpected exception.", e);
824         if (e.getClass().getPackage().getName().matches("javax?\\..+")) {
825             if (e instanceof Exception) {
826                 throw new MBeanException((Exception) e, e.getMessage());
827             }
828 
829             throw new MBeanException(new RuntimeException(e), e.getMessage());
830         }
831 
832         throw new MBeanException(new RuntimeException(e.getClass().getName() + ": " + e.getMessage()), e.getMessage());
833     }
834 
835     protected Object getAttribute0(String fqan) throws Exception {
836         throw new AttributeNotFoundException(fqan);
837     }
838 
839     protected void setAttribute0(String attrName, Object attrValue) throws Exception {
840         throw new AttributeNotFoundException(attrName);
841     }
842 
843     protected Object invoke0(String name, Object params[], String signature[]) throws Exception {
844         throw new NoSuchMethodException();
845     }
846 
847     protected boolean isReadable(Class<?> type, String attrName) {
848         if (IoService.class.isAssignableFrom(type) && attrName.equals("filterChain")) {
849             return false;
850         }
851         if (IoService.class.isAssignableFrom(type) && attrName.equals("localAddress")) {
852             return false;
853         }
854         if (IoService.class.isAssignableFrom(type) && attrName.equals("defaultLocalAddress")) {
855             return false;
856         }
857         if (IoSession.class.isAssignableFrom(type) && attrName.equals("attachment")) {
858             return false;
859         }
860         if (IoSession.class.isAssignableFrom(type) && attrName.equals("attributeKeys")) {
861             return false;
862         }
863         if (IoSession.class.isAssignableFrom(type) && attrName.equals("closeFuture")) {
864             return false;
865         }
866 
867         if (ThreadPoolExecutor.class.isAssignableFrom(type) && attrName.equals("queue")) {
868             return false;
869         }
870 
871         return true;
872     }
873 
874     protected boolean isWritable(Class<?> type, String attrName) {
875         if (IoService.class.isAssignableFrom(type) && attrName.startsWith("defaultLocalAddress")) {
876             return true;
877         }
878         return false;
879     }
880 
881     protected Class<?> getElementType(Class<?> type, String attrName) {
882         if ((transportMetadata != null) && IoAcceptor.class.isAssignableFrom(type)
883                 && "defaultLocalAddresses".equals(attrName)) {
884             return transportMetadata.getAddressType();
885         }
886         return String.class;
887     }
888 
889     protected Class<?> getMapKeyType(Class<?> type, String attrName) {
890         return String.class;
891     }
892 
893     protected Class<?> getMapValueType(Class<?> type, String attrName) {
894         return String.class;
895     }
896 
897     protected boolean isExpandable(Class<?> type, String attrName) {
898 
899         if (IoService.class.isAssignableFrom(type)) {
900             if (attrName.equals("statistics") || attrName.equals("sessionConfig")
901                     || attrName.equals("transportMetadata") || attrName.equals("config")
902                     || attrName.equals("transportMetadata")) {
903                 return true;
904             }
905         }
906 
907         if (ExecutorFilter.class.isAssignableFrom(type) && attrName.equals("executor")) {
908             return true;
909         }
910 
911         if (ThreadPoolExecutor.class.isAssignableFrom(type) && attrName.equals("queueHandler")) {
912             return true;
913         }
914 
915         return false;
916     }
917 
918     protected boolean isOperation(String methodName, Class<?>[] paramTypes) {
919         return true;
920     }
921 
922     protected void addExtraAttributes(List<ModelMBeanAttributeInfo> attributes) {
923         // Do nothing
924     }
925 
926     protected void addExtraOperations(List<ModelMBeanOperationInfo> operations) {
927         // Do nothing
928     }
929 
930     protected PropertyEditor getPropertyEditor(Class<?> type, String attrName, Class<?> attrType) {
931         if (type == null) {
932             throw new IllegalArgumentException("type");
933         }
934 
935         if (attrName == null) {
936             throw new IllegalArgumentException("attrName");
937         }
938 
939         if ((transportMetadata != null) && (attrType == SocketAddress.class)) {
940             attrType = transportMetadata.getAddressType();
941         }
942 
943         if (((attrType == Long.class) || (attrType == long.class))) {
944             if (attrName.endsWith("Time") && (attrName.indexOf("Total") < 0) && (attrName.indexOf("Min") < 0)
945                     && (attrName.indexOf("Max") < 0) && (attrName.indexOf("Avg") < 0)
946                     && (attrName.indexOf("Average") < 0) && !propertyDescriptors.containsKey(attrName + "InMillis")) {
947                 return PropertyEditorFactory.getInstance(Date.class);
948             }
949 
950             if (attrName.equals("id")) {
951                 return PropertyEditorFactory.getInstance(String.class);
952             }
953         }
954 
955         if (List.class.isAssignableFrom(attrType)) {
956             return new ListEditor(getElementType(type, attrName));
957         }
958 
959         if (Set.class.isAssignableFrom(attrType)) {
960             return new SetEditor(getElementType(type, attrName));
961         }
962 
963         if (Collection.class.isAssignableFrom(attrType)) {
964             return new CollectionEditor(getElementType(type, attrName));
965         }
966 
967         if (Map.class.isAssignableFrom(attrType)) {
968             return new MapEditor(getMapKeyType(type, attrName), getMapValueType(type, attrName));
969         }
970 
971         return PropertyEditorFactory.getInstance(attrType);
972     }
973 
974     private class OgnlTypeConverter extends PropertyTypeConverter {
975         @Override
976         protected PropertyEditor getPropertyEditor(Class<?> type, String attrName, Class<?> attrType) {
977             return ObjectMBean.this.getPropertyEditor(type, attrName, attrType);
978         }
979     }
980 }