AnnotatedMBeanTest.java 11.0 KB
Newer Older
1 2 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 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 120 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 181 182 183 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 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337
/*
 * Copyright 2007 Sun Microsystems, Inc.  All Rights Reserved.
 * 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.
 *
 * 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.
 */

/*
 * @test %M% %I%
 * @bug 6323980
 * @summary Test MBeans defined with @MBean
 * @author Eamonn McManus
 * @run main/othervm -ea AnnotatedMBeanTest
 */

import java.io.File;
import java.io.PrintWriter;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
import javax.management.Attribute;
import javax.management.Descriptor;
import javax.management.DescriptorKey;
import javax.management.MBeanAttributeInfo;
import javax.management.MBeanInfo;
import javax.management.MBeanOperationInfo;
import javax.management.MBeanParameterInfo;
import javax.management.MBeanServer;
import javax.management.MBeanServerFactory;
import javax.management.MXBean;
import javax.management.MalformedObjectNameException;
import javax.management.ManagedAttribute;
import javax.management.ManagedOperation;
import javax.management.MBean;
import javax.management.ObjectName;
import javax.management.openmbean.CompositeData;
import javax.management.openmbean.CompositeType;

public class AnnotatedMBeanTest {
    private static MBeanServer mbs;
    private static final ObjectName objectName;
    static {
        try {
            objectName = new ObjectName("test:type=Test");
        } catch (MalformedObjectNameException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws Exception {
        if (!AnnotatedMBeanTest.class.desiredAssertionStatus())
            throw new Exception("Test must be run with -ea");

        File policyFile = File.createTempFile("jmxperms", ".policy");
        policyFile.deleteOnExit();
        PrintWriter pw = new PrintWriter(policyFile);
        pw.println("grant {");
        pw.println("    permission javax.management.MBeanPermission \"*\", \"*\";");
        pw.println("    permission javax.management.MBeanServerPermission \"*\";");
        pw.println("    permission javax.management.MBeanTrustPermission \"*\";");
        pw.println("};");
        pw.close();

        System.setProperty("java.security.policy", policyFile.getAbsolutePath());
        System.setSecurityManager(new SecurityManager());

        String failure = null;

        for (Method m : AnnotatedMBeanTest.class.getDeclaredMethods()) {
            if (Modifier.isStatic(m.getModifiers()) &&
                    m.getName().startsWith("test") &&
                    m.getParameterTypes().length == 0) {
                mbs = MBeanServerFactory.newMBeanServer();
                try {
                    m.invoke(null);
                    System.out.println(m.getName() + " OK");
                } catch (InvocationTargetException ite) {
                    System.out.println(m.getName() + " got exception:");
                    Throwable t = ite.getCause();
                    t.printStackTrace(System.out);
                    failure = m.getName() + ": " + t.toString();
                }
            }
        }
        if (failure == null)
            System.out.println("TEST PASSED");
        else
            throw new Exception("TEST FAILED: " + failure);
    }

    public static class Stats {
        private final int used;
        private final int size;
        private final boolean interesting;

        public Stats(int used, int size, boolean interesting) {
            this.used = used;
            this.size = size;
            this.interesting = interesting;
        }

        public int getUsed() {
            return used;
        }

        public int getSize() {
            return size;
        }

        public boolean isInteresting() {
            return interesting;
        }
    }

    @Retention(RetentionPolicy.RUNTIME)
    public static @interface Units {
        @DescriptorKey("units")
        String value();
    }

    @MBean
    public static class Cache {
        private int used = 23;
        private int size = 99;

        @ManagedAttribute
        @Units("bytes")
        public int getUsed() {
            return used;
        }

        @ManagedAttribute
        public int getSize() {
            return size;
        }

        @ManagedAttribute
        public void setSize(int x) {
            this.size = x;
        }

        @ManagedAttribute
        public boolean isInteresting() {
            return false;
        }

        @ManagedAttribute
        public Stats getStats() {
            return new Stats(used, size, false);
        }

        @ManagedOperation
        public int dropOldest(int n) {
            return 55;
        }

        private void irrelevantMethod() {}
        private int getIrrelevant() {return 0;}
        public int getIrrelevant2() {return 0;}

        public int otherIrrelevantMethod() {return 5;}
    }

    public static class SubCache extends Cache {
        // SubCache does not have the @MBean annotation
        // but its parent does.  It doesn't add any @ManagedAttribute or
        // @ManagedOperation methods, so its management interface
        // should be the same.
        private void irrelevantMethod2() {}
        public int otherIrrelevantMethod3() {return 0;}

        public int getX() {return 0;}
        public void setX(int x) {}
    }

    @MXBean
    public static class CacheMX {
        private int used = 23;
        private int size = 99;

        @ManagedAttribute
        @Units("bytes")
        public int getUsed() {
            return used;
        }

        @ManagedAttribute
        public int getSize() {
            return size;
        }

        @ManagedAttribute
        public void setSize(int x) {
            this.size = x;
        }

        @ManagedAttribute
        public boolean isInteresting() {
            return false;
        }

        @ManagedAttribute
        public Stats getStats() {
            return new Stats(used, size, false);
        }

        @ManagedOperation
        public int dropOldest(int n) {
            return 55;
        }

        private void irrelevantMethod() {}
        private int getIrrelevant() {return 0;}
        public int getIrrelevant2() {return 0;}

        public int otherIrrelevantMethod() {return 5;}
    }

    public static class SubCacheMX extends CacheMX {
        private void irrelevantMethod2() {}
        public int otherIrrelevantMethod3() {return 0;}

        public int getX() {return 0;}
        public void setX(int x) {}
    }

    private static void testSimpleManagedResource() throws Exception {
        testResource(new Cache(), false);
    }

    private static void testSubclassManagedResource() throws Exception {
        testResource(new SubCache(), false);
    }

    private static void testMXBeanResource() throws Exception {
        testResource(new CacheMX(), true);
    }

    private static void testSubclassMXBeanResource() throws Exception {
        testResource(new SubCacheMX(), true);
    }

    private static void testResource(Object resource, boolean mx) throws Exception {
        mbs.registerMBean(resource, objectName);

        MBeanInfo mbi = mbs.getMBeanInfo(objectName);
        assert mbi.getDescriptor().getFieldValue("mxbean").equals(Boolean.toString(mx));

        MBeanAttributeInfo[] mbais = mbi.getAttributes();

        assert mbais.length == 4: mbais.length;

        for (MBeanAttributeInfo mbai : mbais) {
            String name = mbai.getName();
            if (name.equals("Used")) {
                assert mbai.isReadable();
                assert !mbai.isWritable();
                assert !mbai.isIs();
                assert mbai.getType().equals("int");
                assert "bytes".equals(mbai.getDescriptor().getFieldValue("units"));
            } else if (name.equals("Size")) {
                assert mbai.isReadable();
                assert mbai.isWritable();
                assert !mbai.isIs();
                assert mbai.getType().equals("int");
            } else if (name.equals("Interesting")) {
                assert mbai.isReadable();
                assert !mbai.isWritable();
                assert mbai.isIs();
                assert mbai.getType().equals("boolean");
            } else if (name.equals("Stats")) {
                assert mbai.isReadable();
                assert !mbai.isWritable();
                assert !mbai.isIs();
                Descriptor d = mbai.getDescriptor();
                if (mx) {
                    assert mbai.getType().equals(CompositeData.class.getName());
                    assert d.getFieldValue("originalType").equals(Stats.class.getName());
                    CompositeType ct = (CompositeType) d.getFieldValue("openType");
                    Set<String> names = new HashSet<String>(
                            Arrays.asList("used", "size", "interesting"));
                    assert ct.keySet().equals(names) : ct.keySet();
                } else {
                    assert mbai.getType().equals(Stats.class.getName());
                }
            } else
                assert false : name;
        }

        MBeanOperationInfo[] mbois = mbi.getOperations();

        assert mbois.length == 1: mbois.length;

        MBeanOperationInfo mboi = mbois[0];
        assert mboi.getName().equals("dropOldest");
        assert mboi.getReturnType().equals("int");
        MBeanParameterInfo[] mbpis = mboi.getSignature();
        assert mbpis.length == 1: mbpis.length;
        assert mbpis[0].getType().equals("int");

        assert mbs.getAttribute(objectName, "Used").equals(23);

        assert mbs.getAttribute(objectName, "Size").equals(99);
        mbs.setAttribute(objectName, new Attribute("Size", 55));
        assert mbs.getAttribute(objectName, "Size").equals(55);

        assert mbs.getAttribute(objectName, "Interesting").equals(false);

        Object stats = mbs.getAttribute(objectName, "Stats");
        assert (mx ? CompositeData.class : Stats.class).isInstance(stats) : stats.getClass();

        int ret = (Integer) mbs.invoke(
                objectName, "dropOldest", new Object[] {66}, new String[] {"int"});
        assert ret == 55;
    }
}