MBeanAnalyzer.java 11.5 KB
Newer Older
D
duke 已提交
1
/*
X
xdono 已提交
2
 * Copyright 2005-2008 Sun Microsystems, Inc.  All Rights Reserved.
D
duke 已提交
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
 * published by the Free Software Foundation.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
 * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara,
 * CA 95054 USA or visit www.sun.com if you need additional information or
 * have any questions.
 */

package com.sun.jmx.mbeanserver;

import static com.sun.jmx.mbeanserver.Util.*;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.Set;
36 37 38 39
import javax.management.MBean;
import javax.management.MXBean;
import javax.management.ManagedAttribute;
import javax.management.ManagedOperation;
D
duke 已提交
40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
import javax.management.NotCompliantMBeanException;

/**
 * <p>An analyzer for a given MBean interface.  The analyzer can
 * be for Standard MBeans or MXBeans, depending on the MBeanIntrospector
 * passed at construction.
 *
 * <p>The analyzer can
 * visit the attributes and operations of the interface, calling
 * a caller-supplied visitor method for each one.</p>
 *
 * @param <M> Method or ConvertingMethod according as this is a
 * Standard MBean or an MXBean.
 *
 * @since 1.6
 */
class MBeanAnalyzer<M> {

58
    static interface MBeanVisitor<M, X extends Exception> {
D
duke 已提交
59 60
        public void visitAttribute(String attributeName,
                M getter,
61
                M setter) throws X;
D
duke 已提交
62
        public void visitOperation(String operationName,
63
                M operation) throws X;
D
duke 已提交
64 65
    }

66
    <X extends Exception> void visit(MBeanVisitor<M, X> visitor) throws X {
D
duke 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
        // visit attributes
        for (Map.Entry<String, AttrMethods<M>> entry : attrMap.entrySet()) {
            String name = entry.getKey();
            AttrMethods<M> am = entry.getValue();
            visitor.visitAttribute(name, am.getter, am.setter);
        }

        // visit operations
        for (Map.Entry<String, List<M>> entry : opMap.entrySet()) {
            for (M m : entry.getValue())
                visitor.visitOperation(entry.getKey(), m);
        }
    }

    /* Map op name to method */
    private Map<String, List<M>> opMap = newInsertionOrderMap();
    /* Map attr name to getter and/or setter */
    private Map<String, AttrMethods<M>> attrMap = newInsertionOrderMap();

    private static class AttrMethods<M> {
        M getter;
        M setter;
    }

    /**
     * <p>Return an MBeanAnalyzer for the given MBean interface and
     * MBeanIntrospector.  Calling this method twice with the same
     * parameters may return the same object or two different but
     * equivalent objects.
     */
    // Currently it's two different but equivalent objects.  This only
    // really impacts proxy generation.  For MBean creation, the
    // cached PerInterface object for an MBean interface means that
    // an analyzer will not be recreated for a second MBean using the
    // same interface.
102
    static <M> MBeanAnalyzer<M> analyzer(Class<?> mbeanType,
D
duke 已提交
103 104
            MBeanIntrospector<M> introspector)
            throws NotCompliantMBeanException {
105
        return new MBeanAnalyzer<M>(mbeanType, introspector);
D
duke 已提交
106 107
    }

108
    private MBeanAnalyzer(Class<?> mbeanType,
D
duke 已提交
109 110
            MBeanIntrospector<M> introspector)
            throws NotCompliantMBeanException {
111
        introspector.checkCompliance(mbeanType);
D
duke 已提交
112 113

        try {
114
            initMaps(mbeanType, introspector);
D
duke 已提交
115
        } catch (Exception x) {
116
            throw Introspector.throwException(mbeanType,x);
D
duke 已提交
117 118 119 120 121
        }
    }

    // Introspect the mbeanInterface and initialize this object's maps.
    //
122
    private void initMaps(Class<?> mbeanType,
D
duke 已提交
123
            MBeanIntrospector<M> introspector) throws Exception {
124 125
        final List<Method> methods1 = introspector.getMethods(mbeanType);
        final List<Method> methods = eliminateCovariantMethods(methods1);
D
duke 已提交
126 127 128 129

        /* Run through the methods to detect inconsistencies and to enable
           us to give getter and setter together to visitAttribute. */
        for (Method m : methods) {
130 131
            final String name = m.getName();
            final int nParams = m.getParameterTypes().length;
132 133 134 135 136 137
            final boolean managedOp = m.isAnnotationPresent(ManagedOperation.class);
            final boolean managedAttr = m.isAnnotationPresent(ManagedAttribute.class);
            if (managedOp && managedAttr) {
                throw new NotCompliantMBeanException("Method " + name +
                        " has both @ManagedOperation and @ManagedAttribute");
            }
D
duke 已提交
138 139 140 141

            final M cm = introspector.mFrom(m);

            String attrName = "";
142 143 144 145 146 147 148
            if (!managedOp) {
                if (name.startsWith("get"))
                    attrName = name.substring(3);
                else if (name.startsWith("is")
                         && m.getReturnType() == boolean.class)
                    attrName = name.substring(2);
            }
D
duke 已提交
149

150
            if (attrName.length() != 0 && nParams == 0
151
                    && m.getReturnType() != void.class && !managedOp) {
D
duke 已提交
152 153 154 155 156 157 158 159 160 161 162 163 164 165 166
                // It's a getter
                // Check we don't have both isX and getX
                AttrMethods<M> am = attrMap.get(attrName);
                if (am == null)
                    am = new AttrMethods<M>();
                else {
                    if (am.getter != null) {
                        final String msg = "Attribute " + attrName +
                                " has more than one getter";
                        throw new NotCompliantMBeanException(msg);
                    }
                }
                am.getter = cm;
                attrMap.put(attrName, am);
            } else if (name.startsWith("set") && name.length() > 3
167
                    && nParams == 1 &&
168
                    m.getReturnType() == void.class && !managedOp) {
D
duke 已提交
169 170 171 172 173 174 175 176 177 178 179 180
                // It's a setter
                attrName = name.substring(3);
                AttrMethods<M> am = attrMap.get(attrName);
                if (am == null)
                    am = new AttrMethods<M>();
                else if (am.setter != null) {
                    final String msg = "Attribute " + attrName +
                            " has more than one setter";
                    throw new NotCompliantMBeanException(msg);
                }
                am.setter = cm;
                attrMap.put(attrName, am);
181 182 183
            } else if (managedAttr) {
                throw new NotCompliantMBeanException("Method " + name +
                        " has @ManagedAttribute but is not a valid getter or setter");
D
duke 已提交
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243
            } else {
                // It's an operation
                List<M> cms = opMap.get(name);
                if (cms == null)
                    cms = newList();
                cms.add(cm);
                opMap.put(name, cms);
            }
        }
        /* Check that getters and setters are consistent. */
        for (Map.Entry<String, AttrMethods<M>> entry : attrMap.entrySet()) {
            AttrMethods<M> am = entry.getValue();
            if (!introspector.consistent(am.getter, am.setter)) {
                final String msg = "Getter and setter for " + entry.getKey() +
                        " have inconsistent types";
                throw new NotCompliantMBeanException(msg);
            }
        }
    }

    /**
     * A comparator that defines a total order so that methods have the
     * same name and identical signatures appear next to each others.
     * The methods are sorted in such a way that methods which
     * override each other will sit next to each other, with the
     * overridden method first - e.g. Object getFoo() is placed before
     * Integer getFoo(). This makes it possible to determine whether
     * a method overrides another one simply by looking at the method(s)
     * that precedes it in the list. (see eliminateCovariantMethods).
     **/
    private static class MethodOrder implements Comparator<Method> {
        public int compare(Method a, Method b) {
            final int cmp = a.getName().compareTo(b.getName());
            if (cmp != 0) return cmp;
            final Class<?>[] aparams = a.getParameterTypes();
            final Class<?>[] bparams = b.getParameterTypes();
            if (aparams.length != bparams.length)
                return aparams.length - bparams.length;
            if (!Arrays.equals(aparams, bparams)) {
                return Arrays.toString(aparams).
                        compareTo(Arrays.toString(bparams));
            }
            final Class<?> aret = a.getReturnType();
            final Class<?> bret = b.getReturnType();
            if (aret == bret) return 0;

            // Super type comes first: Object, Number, Integer
            if (aret.isAssignableFrom(bret))
                return -1;
            return +1;      // could assert bret.isAssignableFrom(aret)
        }
        public final static MethodOrder instance = new MethodOrder();
    }


    /* Eliminate methods that are overridden with a covariant return type.
       Reflection will return both the original and the overriding method
       but only the overriding one is of interest.  We return the methods
       in the same order they arrived in.  This isn't required by the spec
       but existing code may depend on it and users may be used to seeing
244 245 246 247 248
       operations or attributes appear in a particular order.

       Because of the way this method works, if the same Method appears
       more than once in the given List then it will be completely deleted!
       So don't do that.  */
D
duke 已提交
249
    static List<Method>
250
            eliminateCovariantMethods(List<Method> startMethods) {
D
duke 已提交
251 252 253 254
        // We are assuming that you never have very many methods with the
        // same name, so it is OK to use algorithms that are quadratic
        // in the number of methods with the same name.

255 256
        final int len = startMethods.size();
        final Method[] sorted = startMethods.toArray(new Method[len]);
D
duke 已提交
257 258 259 260 261 262
        Arrays.sort(sorted,MethodOrder.instance);
        final Set<Method> overridden = newSet();
        for (int i=1;i<len;i++) {
            final Method m0 = sorted[i-1];
            final Method m1 = sorted[i];

263
            // Methods that don't have the same name can't override each other
D
duke 已提交
264 265 266 267 268 269 270
            if (!m0.getName().equals(m1.getName())) continue;

            // Methods that have the same name and same signature override
            // each other. In that case, the second method overrides the first,
            // due to the way we have sorted them in MethodOrder.
            if (Arrays.equals(m0.getParameterTypes(),
                    m1.getParameterTypes())) {
271 272
                if (!overridden.add(m0))
                    throw new RuntimeException("Internal error: duplicate Method");
D
duke 已提交
273 274 275
            }
        }

276
        final List<Method> methods = newList(startMethods);
D
duke 已提交
277 278 279 280 281 282
        methods.removeAll(overridden);
        return methods;
    }


}