CompositeDataInvocationHandler.java 10.0 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
 * 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 javax.management.openmbean;

import com.sun.jmx.mbeanserver.MXBeanLookup;
29 30
import com.sun.jmx.mbeanserver.MXBeanMapping;
import com.sun.jmx.mbeanserver.MXBeanMappingFactory;
31
import com.sun.jmx.mbeanserver.DefaultMXBeanMappingFactory;
D
duke 已提交
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 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 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
   <p>An {@link InvocationHandler} that forwards getter methods to a
   {@link CompositeData}.  If you have an interface that contains
   only getter methods (such as {@code String getName()} or
   {@code boolean isActive()}) then you can use this class in
   conjunction with the {@link Proxy} class to produce an implementation
   of the interface where each getter returns the value of the
   corresponding item in a {@code CompositeData}.</p>

   <p>For example, suppose you have an interface like this:

   <blockquote>
   <pre>
   public interface NamedNumber {
       public int getNumber();
       public String getName();
   }
   </pre>
   </blockquote>

   and a {@code CompositeData} constructed like this:

   <blockquote>
   <pre>
   CompositeData cd =
       new {@link CompositeDataSupport}(
           someCompositeType,
           new String[] {"number", "name"},
           new Object[] {<b>5</b>, "five"}
       );
   </pre>
   </blockquote>

   then you can construct an object implementing {@code NamedNumber}
   and backed by the object {@code cd} like this:

   <blockquote>
   <pre>
   InvocationHandler handler =
       new CompositeDataInvocationHandler(cd);
   NamedNumber nn = (NamedNumber)
       Proxy.newProxyInstance(NamedNumber.class.getClassLoader(),
                              new Class[] {NamedNumber.class},
                              handler);
   </pre>
   </blockquote>

   A call to {@code nn.getNumber()} will then return <b>5</b>.</p>

   <p>If the first letter of the property defined by a getter is a
   capital, then this handler will look first for an item in the
   {@code CompositeData} beginning with a capital, then, if that is
   not found, for an item beginning with the corresponding lowercase
   letter or code point.  For a getter called {@code getNumber()}, the
   handler will first look for an item called {@code Number}, then for
   {@code number}.  If the getter is called {@code getnumber()}, then
   the item must be called {@code number}.</p>

   <p>If the method given to {@link #invoke invoke} is the method
   {@code boolean equals(Object)} inherited from {@code Object}, then
   it will return true if and only if the argument is a {@code Proxy}
   whose {@code InvocationHandler} is also a {@code
   CompositeDataInvocationHandler} and whose backing {@code
   CompositeData} is equal (not necessarily identical) to this
   object's.  If the method given to {@code invoke} is the method
   {@code int hashCode()} inherited from {@code Object}, then it will
   return a value that is consistent with this definition of {@code
   equals}: if two objects are equal according to {@code equals}, then
   they will have the same {@code hashCode}.</p>

   @since 1.6
*/
public class CompositeDataInvocationHandler implements InvocationHandler {
    /**
       <p>Construct a handler backed by the given {@code
       CompositeData}.</p>

       @param compositeData the {@code CompositeData} that will supply
       information to getters.

       @throws IllegalArgumentException if {@code compositeData}
       is null.
    */
    public CompositeDataInvocationHandler(CompositeData compositeData) {
120
        this(compositeData, null);
D
duke 已提交
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180
    }

    /**
       <p>Construct a handler backed by the given {@code
       CompositeData}.</p>

       @param mbsc the {@code MBeanServerConnection} related to this
       {@code CompositeData}.  This is only relevant if a method in
       the interface for which this is an invocation handler returns
       a type that is an MXBean interface.  Otherwise, it can be null.

       @param compositeData the {@code CompositeData} that will supply
       information to getters.

       @throws IllegalArgumentException if {@code compositeData}
       is null.
    */
    CompositeDataInvocationHandler(CompositeData compositeData,
                                   MXBeanLookup lookup) {
        if (compositeData == null)
            throw new IllegalArgumentException("compositeData");
        this.compositeData = compositeData;
        this.lookup = lookup;
    }

    /**
       Return the {@code CompositeData} that was supplied to the
       constructor.
       @return the {@code CompositeData} that this handler is backed
       by.  This is never null.
    */
    public CompositeData getCompositeData() {
        assert compositeData != null;
        return compositeData;
    }

    public Object invoke(Object proxy, Method method, Object[] args)
            throws Throwable {
        final String methodName = method.getName();

        // Handle the methods from java.lang.Object
        if (method.getDeclaringClass() == Object.class) {
            if (methodName.equals("toString") && args == null)
                return "Proxy[" + compositeData + "]";
            else if (methodName.equals("hashCode") && args == null)
                return compositeData.hashCode() + 0x43444948;
            else if (methodName.equals("equals") && args.length == 1
                && method.getParameterTypes()[0] == Object.class)
                return equals(proxy, args[0]);
            else {
                /* Either someone is calling invoke by hand, or
                   it is a non-final method from Object overriden
                   by the generated Proxy.  At the time of writing,
                   the only non-final methods in Object that are not
                   handled above are finalize and clone, and these
                   are not overridden in generated proxies.  */
                return method.invoke(this, args);
            }
        }

181
        String propertyName = DefaultMXBeanMappingFactory.propertyName(method);
D
duke 已提交
182 183 184 185 186 187 188 189
        if (propertyName == null) {
            throw new IllegalArgumentException("Method is not getter: " +
                                               method.getName());
        }
        Object openValue;
        if (compositeData.containsKey(propertyName))
            openValue = compositeData.get(propertyName);
        else {
190
            String decap = DefaultMXBeanMappingFactory.decapitalize(propertyName);
D
duke 已提交
191 192 193 194 195 196 197 198 199 200
            if (compositeData.containsKey(decap))
                openValue = compositeData.get(decap);
            else {
                final String msg =
                    "No CompositeData item " + propertyName +
                    (decap.equals(propertyName) ? "" : " or " + decap) +
                    " to match " + methodName;
                throw new IllegalArgumentException(msg);
            }
        }
201
        MXBeanMapping mapping =
202
            MXBeanMappingFactory.DEFAULT.mappingForType(method.getGenericReturnType(),
203 204
                                   MXBeanMappingFactory.DEFAULT);
        return mapping.fromOpenValue(openValue);
D
duke 已提交
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
    }

    /* This method is called when equals(Object) is
     * called on our proxy and hence forwarded to us.  For example, if we
     * are a proxy for an interface like this:
     * public interface GetString {
     *     public String string();
     * }
     * then we must compare equal to another CompositeDataInvocationHandler
     * proxy for the same interface and where string() returns the same value.
     *
     * You might think that we should also compare equal to another
     * object that implements GetString directly rather than using
     * Proxy, provided that its string() returns the same result as
     * ours, and in fact an earlier version of this class did that (by
     * converting the other object into a CompositeData and comparing
     * that with ours).  But in fact that doesn't make a great deal of
     * sense because there's absolutely no guarantee that the
     * resulting equals would be reflexive (otherObject.equals(this)
     * might be false even if this.equals(otherObject) is true), and,
     * especially, there's no way we could generate a hashCode() that
     * would be equal to otherObject.hashCode() when
     * this.equals(otherObject), because we don't know how
     * otherObject.hashCode() is computed.
     */
    private boolean equals(Object proxy, Object other) {
        if (other == null)
            return false;

234 235
        final Class<?> proxyClass = proxy.getClass();
        final Class<?> otherClass = other.getClass();
D
duke 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248
        if (proxyClass != otherClass)
            return false;
        InvocationHandler otherih = Proxy.getInvocationHandler(other);
        if (!(otherih instanceof CompositeDataInvocationHandler))
            return false;
        CompositeDataInvocationHandler othercdih =
            (CompositeDataInvocationHandler) otherih;
        return compositeData.equals(othercdih.compositeData);
    }

    private final CompositeData compositeData;
    private final MXBeanLookup lookup;
}