NamedMBeanServerTest.java 17.0 KB
Newer Older
1
/*
X
xdono 已提交
2
 * Copyright 2003-2008 Sun Microsystems, Inc.  All Rights Reserved.
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
 * 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
 * @summary Test named MBeanServers.
 * @author Daniel Fuchs
28
 * @bug 6299231
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 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441
 * @run clean NamedMBeanServerTest
 * @run build NamedMBeanServerTest
 * @run main NamedMBeanServerTest
 */

import java.util.Arrays;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.management.MBeanServer;
import javax.management.MBeanServerBuilder;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerFactory;

/**
 * This test can probably be leveraged in the JCK to test compatibilty
 * of MBeanServerFactory *Name* method implementation.
 * @author dfuchs
 */
public class NamedMBeanServerTest {

    /**
     * One enum value for each way of creating an MBeanServer through the
     * MBeanServerFactory
     */
    public static enum Creator {
        newMBeanServer() {
            public MBeanServer create(String domain) {
                return MBeanServerFactory.newMBeanServer(domain);
            }
            public String test(MBeanServer server, String domain) {
                System.out.println(toString()+"("+domain+")");
                return test(server,
                        MBeanServerFactory.DEFAULT_MBEANSERVER_NAME,
                        domain);
            }
            public MBeanServer[] servers(Config config) {
                return config.ndServers;
            }
            public String[] strings(Config config) {
                return domains(config);
            }
            public String[] domains(Config config) {
                return config.newDomains;
            }
            public String[] names(Config config) {
                return null;
            }
        },
        createMBeanServer() {
            public MBeanServer create(String domain) {
                return MBeanServerFactory.createMBeanServer(domain);
            }
            public String test(MBeanServer server, String domain) {
                System.out.println(toString()+"("+domain+")");
                return test(server,MBeanServerFactory.DEFAULT_MBEANSERVER_NAME,
                        domain);
            }
            public MBeanServer[] servers(Config config) {
                return config.cdServers;
            }
            public String[] strings(Config config) {
                return domains(config);
            }
            public String[] domains(Config config) {
                return config.createDomains;
            }
            public String[] names(Config config) {
                return null;
            }
        },
        newNamedMBeanServer() {
            public MBeanServer create(String name) {
                return MBeanServerFactory.newNamedMBeanServer(name,null);
            }
            public String test(MBeanServer server, String name) {
                System.out.println(toString()+"("+name+",null)");
                return test(server,name,"DefaultDomain");
            }
            public MBeanServer[] servers(Config config) {
                return config.nnServers;
            }
            public String[] strings(Config config) {
                return names(config);
            }
            public String[] domains(Config config) {
                return null;
            }
            public String[] names(Config config) {
                return config.newNames;
            }
        },
        createNamedMBeanServer() {
            public MBeanServer create(String name) {
                return MBeanServerFactory.createNamedMBeanServer(name,null);
            }
            public String test(MBeanServer server, String name) {
                System.out.println(toString()+"("+name+",null)");
                return test(server,name,"DefaultDomain");
            }
            public MBeanServer[] servers(Config config) {
                return config.cnServers;
            }
            public String[] strings(Config config) {
                return names(config);
            }
            public String[] domains(Config config) {
                return null;
            }
            public String[] names(Config config) {
                return config.createNames;
            }
        };

        // creates an MBeanServer using the specified input string.
        // either a domain, (for UNNAMED) or a mbeanServerName (for NAMED)
        public abstract MBeanServer create(String string);

        // test the created server against the string used as input to create
        // it.
        public abstract String test(MBeanServer server, String ref);

        public abstract MBeanServer[] servers(Config config);
        public abstract String[] strings(Config config);
        public abstract String[] names(Config config);
        public abstract String[] domains(Config config);

        public MBeanServer[] servers(Config config, String... refs) {
            final MBeanServer[] servers = servers(config);
            final String[] strings = strings(config);
            final MBeanServer[] res = new MBeanServer[refs.length];
            for (int i=0;i<refs.length;i++) {
                for (int j=0;j<strings.length;j++) {
                    if (strings[j].equals(refs[i]))
                        res[i]=servers[j];
                }
                if (res[i] == null)
                    throw new IllegalArgumentException(refs[i]);
            }
            return res;
        }

        String test(MBeanServer server, String name, String domain) {
            // whether the MBeanServer was created throug a "create" method
            boolean registered = REFERENCED.contains(this);
            if (!server.getDefaultDomain().equals(domain)) {
                return "Unexpected default domain: " +
                        server.getDefaultDomain() + ", should be: " + domain;
            }
            if (!MBeanServerFactory.getMBeanServerName(server).
                    equals(name)) {
                return " Unexpected name: " +
                        MBeanServerFactory.getMBeanServerName(server) +
                        ", should be: " + name;
            }
            List<MBeanServer> found =
                    MBeanServerFactory.findMBeanServerByName(name);
            if (!registered && found.contains(server))
                return " Server "+name+" found by name - " +
                        "but should not be registered";
            if (!registered &&
                    !name.equals(MBeanServerFactory.DEFAULT_MBEANSERVER_NAME) &&
                    found.size()>0)
                return " Server "+name+" had too many matches: " + found.size();
            if (registered && !found.contains(server))
                return " Server "+name+" not found by name - " +
                        "but is registered!";
            if (registered &&
                    !name.equals(MBeanServerFactory.DEFAULT_MBEANSERVER_NAME) &&
                    !(found.size()==1))
                return " Server "+name+" had too many matches: " + found.size();
            return null;
        }

        public static final EnumSet<Creator> NAMED =
                EnumSet.of(createNamedMBeanServer, newNamedMBeanServer);
        public static final EnumSet<Creator> UNNAMED =
                EnumSet.complementOf(NAMED);
        public static final EnumSet<Creator> REFERENCED =
                EnumSet.of(createMBeanServer, createNamedMBeanServer);
        public static final EnumSet<Creator> UNREFERENCED =
                EnumSet.complementOf(REFERENCED);

    }

    public static class Config {
        final String[] newDomains;
        final String[] createDomains;
        final String[] newNames;
        final String[] createNames;
        final MBeanServer[] ndServers;
        final MBeanServer[] cdServers;
        final MBeanServer[] nnServers;
        final MBeanServer[] cnServers;
        final Map<String,Set<MBeanServer>> queries;
        Config(String[][] data) {
            this(data[0],data[1],data[2],data[3]);
        }
        Config(String[] nd, String[] cd, String[] nn, String[] cn) {
            this.newDomains=nd.clone();
            this.createDomains=cd.clone();
            this.newNames=nn.clone();
            this.createNames=cn.clone();
            ndServers = new MBeanServer[nd.length];
            cdServers = new MBeanServer[cd.length];
            nnServers = new MBeanServer[nn.length];
            cnServers = new MBeanServer[cn.length];
            queries = new HashMap<String,Set<MBeanServer>>();
            init();
        }
        private void init() {
            for (Creator c : Creator.values()) fill(c);
            addQuery(null,Creator.createMBeanServer.servers(this));
            addQuery(null,Creator.createNamedMBeanServer.servers(this));
            addQuery("?*",Creator.createMBeanServer.servers(this));
            addQuery("?*",Creator.createNamedMBeanServer.servers(this));
            addQuery("*",Creator.createMBeanServer.servers(this));
            addQuery("*",Creator.createNamedMBeanServer.servers(this));
            addQuery(MBeanServerFactory.DEFAULT_MBEANSERVER_NAME,
                    Creator.createMBeanServer.servers(this));
        }
        private void addQuery(String pattern, MBeanServer... servers) {
            final Set<MBeanServer> s = getQuery(pattern);
            s.addAll(Arrays.asList(servers));
        }
        public Set<MBeanServer> getQuery(String pattern) {
            final Set<MBeanServer> s = queries.get(pattern);
            if (s != null) return s;
            queries.put(pattern,new HashSet<MBeanServer>());
            return queries.get(pattern);
        }
        public Set<String> getPatterns() {
            return queries.keySet();
        }
        private void fill(Creator creator) {
            fill(creator.servers(this),creator.strings(this),creator);
        }
        private void fill(MBeanServer[] dest, String[] src, Creator creator) {
            for(int i=0;i<src.length;i++) dest[i]=creator.create(src[i]);
        }

    }

    static String[] domains(String... str) {
        return str;
    }
    static String[] names(String... str) {
        return str;
    }
    final static Config test1  = new Config(domains("foo1","foo2","foo3"),
            domains("foobar1","foobar2","foobar3","foobar4"),
            names("bar1","bar2"),
            names("barfoo1","barfoo2","barfoo3","batfox1","catfog2","foofoo3"));
    static {
        test1.addQuery("b*",Creator.createNamedMBeanServer.servers(test1,
                "barfoo1","barfoo2","barfoo3","batfox1"));
        test1.addQuery("*arf*",Creator.createNamedMBeanServer.servers(test1,
                "barfoo1","barfoo2","barfoo3"));
        test1.addQuery("*a?f*",Creator.createNamedMBeanServer.servers(test1,
                "barfoo1","barfoo2","barfoo3","batfox1","catfog2"));
        test1.addQuery("",new MBeanServer[0]);
        test1.addQuery("-",new MBeanServer[0]);
        test1.addQuery("def*",Creator.createMBeanServer.servers(test1));
    }

    public static void test(Config config) throws Exception {
        for (Creator c : Creator.values()) {
            final MBeanServer[] s = c.servers(config);
            final String[] ref = c.strings(config);
            for (int i=0;i<s.length;i++) {
                final String msg = c.test(s[i], ref[i]);
                if (msg != null)
                    throw new Exception(String.valueOf(c)+"["+i+"]: "+msg);
            }
        }
        for (String pat : config.getPatterns()) {
            System.out.print("findMBeanServerByName(\""+pat+"\"): [");
            final List<MBeanServer> found =
                    MBeanServerFactory.findMBeanServerByName(pat);
            String sep=" ";
            for (MBeanServer m : found) {
                System.out.print(sep+MBeanServerFactory.getMBeanServerName(m));
                sep=", ";
            }
            System.out.println(" ]");
            final Set<MBeanServer> founds = new HashSet<MBeanServer>();
            founds.addAll(found);
            if (!founds.equals(config.getQuery(pat))) {
                final String msg =
                        "bad result for findMBeanServerByName(\""+
                        pat+"\"): expected "+config.getQuery(pat).size()+", "+
                        "got "+founds.size();
                throw new Exception(msg);
            }
        }
    }

    public static void testexception(Creator c, String name,
            Class<? extends Exception> error) throws Exception {
        Exception failed = null;
        MBeanServer server = null;
        try {
            server = c.create(name);
        } catch (Exception x) {
            failed = x;
        } finally {
            if (Creator.REFERENCED.contains(c) && server!=null) {
                MBeanServerFactory.releaseMBeanServer(server);
            }
        }
        if (failed == null && error != null) {
            throw new Exception("Expected "+error.getName()+
                    " for "+c+"("+name+")");
        }
        if (error != null && !error.isInstance(failed))
            throw new Exception("Expected "+error.getName()+
                    " for "+c+"("+name+"), caught "+failed);
        System.out.println(""+c+"("+name+") PASSED: "+
                (failed==null?"no exception":String.valueOf(failed)));
    }

    private static final Map<String,Class<? extends Exception>> failures =
            new LinkedHashMap<String,Class<? extends Exception>>();
    private static final Map<String,Class<? extends Exception>> legacy =
            new LinkedHashMap<String,Class<? extends Exception>>();
    private static final String[] illegalnames = {
        "", "-", ":", ";", "?", "*", "wom?bat", "ran:tan.plan",
        "rin;tin.tin", "tab*mow"

    };
    private static final String[] legalnames = {
        "wombat", "top.tip", "ran.tan.plan", "rin.tin.tin!"
    };
    private static final String[] nofailures = {
       MBeanServerFactory.DEFAULT_MBEANSERVER_NAME, "default", null
    };
    static {
        for (String s:illegalnames)
            failures.put(s, IllegalArgumentException.class);
        for (String s:nofailures)
            failures.put(s, null);
        legacy.putAll(failures);
        for (String s:legalnames)
            legacy.put(s, UnsupportedOperationException.class);

    }

    public static void test2(Map<String,Class<? extends Exception>> config)
        throws Exception {
        for (Creator c:Creator.NAMED) {
            for (String s:config.keySet()) testexception(c, s, config.get(s));
        }
    }

    public static class LegacyBuilder extends MBeanServerBuilder {

        @Override
        public MBeanServerDelegate newMBeanServerDelegate() {
            return new MBeanServerDelegate() {
                @Override
                public synchronized String getMBeanServerId() {
                    return "gloups";
                }
            };
        }

    }
    public static class LegacyBuilder2 extends MBeanServerBuilder {

        @Override
        public MBeanServerDelegate newMBeanServerDelegate() {
            return new MBeanServerDelegate() {
                @Override
                public synchronized String getMBeanServerId() {
                    return "c'est la vie...";
                }
                @Override
                public synchronized void setMBeanServerName(String name) {
                }

            };
        }

    }

    public static void test3(Map<String,Class<? extends Exception>> config,
            String builderClassName)
        throws Exception {
        final String builder =
                System.getProperty("javax.management.builder.initial");
        System.setProperty("javax.management.builder.initial",
                builderClassName);
        try {
            test2(config);
        } finally {
            if (builder != null)
                System.setProperty("javax.management.builder.initial", builder);
            else
                System.clearProperty("javax.management.builder.initial");
        }
    }

    public static void main(String[] args) throws Exception {
        test(test1);
        test2(failures);
        test3(legacy,LegacyBuilder.class.getName());
        test3(legacy,LegacyBuilder2.class.getName());
    }
}