NotificationInfoTest.java 11.0 KB
Newer Older
D
duke 已提交
1
/*
X
xdono 已提交
2
 * Copyright 2004-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.
 *
 * 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
 * @bug 5012634
 * @summary Test that JMX classes use fully-qualified class names
 * in MBeanNotificationInfo
 * @author Eamonn McManus
 * @run clean NotificationInfoTest
 * @run build NotificationInfoTest
 * @run main NotificationInfoTest
 */

import java.io.*;
36
import java.lang.management.*;
D
duke 已提交
37 38 39 40 41 42 43
import java.lang.reflect.*;
import java.net.*;
import java.security.CodeSource;
import java.util.*;
import java.util.jar.*;
import javax.management.*;
import javax.management.relation.*;
44 45
import javax.management.remote.*;
import javax.management.remote.rmi.*;
D
duke 已提交
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

/*
 * This test finds all classes in the same code-base as the JMX
 * classes that look like Standard MBeans, and checks that if they are
 * NotificationBroadcasters they declare existent notification types.
 * A class looks like a Standard MBean if both Thing and ThingMBean
 * classes exist.  So for example javax.management.timer.Timer looks
 * like a Standard MBean because javax.management.timer.TimerMBean
 * exists.  Timer is instanceof NotificationBroadcaster, so we expect
 * that ((NotificationBroadcaster) timer).getNotificationInfo() will
 * return an array of MBeanNotificationInfo where each entry has a
 * getName() that names an existent Java class that is a Notification.
 *
 * An MBean is "suspicious" if it is a NotificationBroadcaster but its
 * MBeanNotificationInfo[] is empty.  This is legal, but surprising.
 *
 * In order to call getNotificationInfo(), we need an instance of the
 * class.  We attempt to make one by calling a public no-arg
 * constructor.  But the "construct" method below can be extended to
 * construct specific MBean classes for which the no-arg constructor
 * doesn't exist.
 *
 * The test is obviously not exhaustive, but does catch the cases that
 * failed in 5012634.
 */
public class NotificationInfoTest {
    // class or object names where the test failed
73
    private static final Set<String> failed = new TreeSet<String>();
D
duke 已提交
74 75

    // class or object names where there were no MBeanNotificationInfo entries
76
    private static final Set<String> suspicious = new TreeSet<String>();
D
duke 已提交
77 78 79 80 81 82 83 84 85 86 87 88 89 90

    public static void main(String[] args) throws Exception {
        System.out.println("Checking that all known MBeans that are " +
                           "NotificationBroadcasters have sane " +
                           "MBeanInfo.getNotifications()");

        System.out.println("Checking platform MBeans...");
        checkPlatformMBeans();

        CodeSource cs =
            javax.management.MBeanServer.class.getProtectionDomain()
            .getCodeSource();
        URL codeBase;
        if (cs == null) {
91 92 93 94 95 96 97 98 99 100 101 102 103 104
            String javaHome = System.getProperty("java.home");
            String[] candidates = {"/lib/rt.jar", "/classes/"};
            codeBase = null;
            for (String candidate : candidates) {
                File file = new File(javaHome + candidate);
                if (file.exists()) {
                    codeBase = file.toURI().toURL();
                    break;
                }
            }
            if (codeBase == null) {
                throw new Exception(
                        "Could not determine codeBase for java.home=" + javaHome);
            }
D
duke 已提交
105 106 107 108 109 110 111 112 113 114
        } else
            codeBase = cs.getLocation();

        System.out.println();
        System.out.println("Looking for standard MBeans...");
        String[] classes = findStandardMBeans(codeBase);

        System.out.println("Testing standard MBeans...");
        for (int i = 0; i < classes.length; i++) {
            String name = classes[i];
115
            Class<?> c;
D
duke 已提交
116 117 118 119 120 121 122 123 124 125
            try {
                c = Class.forName(name);
            } catch (Throwable e) {
                System.out.println(name + ": cannot load (not public?): " + e);
                continue;
            }
            if (!NotificationBroadcaster.class.isAssignableFrom(c)) {
                System.out.println(name + ": not a NotificationBroadcaster");
                continue;
            }
126 127 128 129
            if (Modifier.isAbstract(c.getModifiers())) {
                System.out.println(name + ": abstract class");
                continue;
            }
D
duke 已提交
130 131

            NotificationBroadcaster mbean;
132
            Constructor<?> constr;
D
duke 已提交
133
            try {
134
                constr = c.getConstructor();
D
duke 已提交
135 136 137 138 139 140
            } catch (Exception e) {
                System.out.println(name + ": no public no-arg constructor: "
                                   + e);
                continue;
            }
            try {
141
                mbean = (NotificationBroadcaster) constr.newInstance();
D
duke 已提交
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
            } catch (Exception e) {
                System.out.println(name + ": no-arg constructor failed: " + e);
                continue;
            }

            check(mbean);
        }

        System.out.println();
        System.out.println("Testing some explicit cases...");

        check(new RelationService(false));
        /*
          We can't do this:
            check(new RequiredModelMBean());
          because the Model MBean spec more or less forces us to use the
          names GENERIC and ATTRIBUTE_CHANGE for its standard notifs.
        */
        checkRMIConnectorServer();

        System.out.println();
        if (!suspicious.isEmpty())
            System.out.println("SUSPICIOUS CLASSES: " + suspicious);

        if (failed.isEmpty())
            System.out.println("TEST PASSED");
        else {
            System.out.println("TEST FAILED: " + failed);
            System.exit(1);
        }
    }

    private static void check(NotificationBroadcaster mbean)
            throws Exception {
        System.out.print(mbean.getClass().getName() + ": ");

        check(mbean.getClass().getName(), mbean.getNotificationInfo());
    }

    private static void checkPlatformMBeans() throws Exception {
182 183 184
        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
        Set<ObjectName> mbeanNames = mbs.queryNames(null, null);
        for (ObjectName name : mbeanNames) {
D
duke 已提交
185 186 187 188 189 190 191 192 193 194 195
            if (!mbs.isInstanceOf(name,
                                  NotificationBroadcaster.class.getName())) {
                System.out.println(name + ": not a NotificationBroadcaster");
            } else {
                MBeanInfo mbi = mbs.getMBeanInfo(name);
                check(name.toString(), mbi.getNotifications());
            }
        }
    }

    private static void checkRMIConnectorServer() throws Exception {
196 197 198
        JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");
        RMIConnectorServer connector = new RMIConnectorServer(url, null);
        check(connector);
D
duke 已提交
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
    }

    private static void check(String what, MBeanNotificationInfo[] mbnis) {
        System.out.print(what + ": checking notification info: ");

        if (mbnis.length == 0) {
            System.out.println("NONE (suspicious)");
            suspicious.add(what);
            return;
        }

        // Each MBeanNotificationInfo.getName() should be an existent
        // Java class that is Notification or a subclass of it
        for (int j = 0; j < mbnis.length; j++) {
            String notifClassName = mbnis[j].getName();
                Class notifClass;
                try {
                    notifClass = Class.forName(notifClassName);
                } catch (Exception e) {
                    System.out.print("FAILED(" + notifClassName + ": " + e +
                                     ") ");
                    failed.add(what);
                    continue;
                }
                if (!Notification.class.isAssignableFrom(notifClass)) {
                    System.out.print("FAILED(" + notifClassName +
                                     ": not a Notification) ");
                    failed.add(what);
                    continue;
                }
                System.out.print("OK(" + notifClassName + ") ");
        }
        System.out.println();
    }

    private static String[] findStandardMBeans(URL codeBase)
            throws Exception {
236
        Set<String> names;
D
duke 已提交
237 238 239 240 241 242
        if (codeBase.getProtocol().equalsIgnoreCase("file")
            && codeBase.toString().endsWith("/"))
            names = findStandardMBeansFromDir(codeBase);
        else
            names = findStandardMBeansFromJar(codeBase);

243 244
        Set<String> standardMBeanNames = new TreeSet<String>();
        for (String name : names) {
D
duke 已提交
245 246 247 248 249 250
            if (name.endsWith("MBean")) {
                String prefix = name.substring(0, name.length() - 5);
                if (names.contains(prefix))
                    standardMBeanNames.add(prefix);
            }
        }
251
        return standardMBeanNames.toArray(new String[0]);
D
duke 已提交
252 253
    }

254
    private static Set<String> findStandardMBeansFromJar(URL codeBase)
D
duke 已提交
255 256 257
            throws Exception {
        InputStream is = codeBase.openStream();
        JarInputStream jis = new JarInputStream(is);
258
        Set<String> names = new TreeSet<String>();
D
duke 已提交
259 260 261 262 263 264 265 266 267 268 269 270
        JarEntry entry;
        while ((entry = jis.getNextJarEntry()) != null) {
            String name = entry.getName();
            if (!name.endsWith(".class"))
                continue;
            name = name.substring(0, name.length() - 6);
            name = name.replace('/', '.');
            names.add(name);
        }
        return names;
    }

271
    private static Set<String> findStandardMBeansFromDir(URL codeBase)
D
duke 已提交
272 273
            throws Exception {
        File dir = new File(new URI(codeBase.toString()));
274
        Set<String> names = new TreeSet<String>();
D
duke 已提交
275 276 277 278
        scanDir(dir, "", names);
        return names;
    }

279
    private static void scanDir(File dir, String prefix, Set<String> names)
D
duke 已提交
280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296
            throws Exception {
        File[] files = dir.listFiles();
        if (files == null)
            return;
        for (int i = 0; i < files.length; i++) {
            File f = files[i];
            String name = f.getName();
            String p = (prefix.equals("")) ? name : prefix + "." + name;
            if (f.isDirectory())
                scanDir(f, p, names);
            else if (name.endsWith(".class")) {
                p = p.substring(0, p.length() - 6);
                names.add(p);
            }
        }
    }
}