aboutsummaryrefslogtreecommitdiff
path: root/test/javax/management/namespace/QueryNamesTest.java
blob: 1af597aceb938b10ee70e0f5201711b827bd4afe (plain)
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
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
/*
 * Copyright 2008 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 QueryNamesTest.java 1.4
 * @summary Test how queryNames works with Namespaces.
 * @author Daniel Fuchs
 * @bug 5072476
 * @run clean QueryNamesTest Wombat WombatMBean
 * @run build QueryNamesTest Wombat WombatMBean
 * @run main QueryNamesTest
 */


import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.logging.Logger;
import javax.management.InstanceNotFoundException;
import javax.management.JMException;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.MalformedObjectNameException;
import javax.management.ObjectName;
import javax.management.namespace.JMXNamespace;
import javax.management.namespace.JMXNamespaces;

/**
 * Class QueryNamesTest
 * @author Sun Microsystems, 2005 - All rights reserved.
 */
public class QueryNamesTest {

    /**
     * A logger for this class.
     **/
    private static final Logger LOG =
            Logger.getLogger(QueryNamesTest.class.getName());

    public static class LocalNamespace
            extends JMXNamespace {

        private static MBeanServer check(MBeanServer server) {
            if (server == null)
                throw new IllegalArgumentException("MBeanServer can't be null");
            return server;
        }

        public LocalNamespace() {
            this(MBeanServerFactory.createMBeanServer());
        }

        public LocalNamespace(MBeanServer server) {
            super(check(server));
        }


        public static String add(MBeanServerConnection server,
                String nspath)
                throws IOException, JMException {
            server.createMBean(LocalNamespace.class.getName(),
                    JMXNamespaces.getNamespaceObjectName(nspath));
            return nspath;
        }
    }

    /** Creates a new instance of QueryNamesTest */
    public QueryNamesTest() {
    }

    private static String[] namespaces = {
        "greg", "greg//chichille", "greg//chichille//petard",
        "greg//alambic", "greg//alambic//canette",
        "greg//chichille/virgule", "greg//chichille/funeste",
        "greg//chichille/virgule//bidouble",
        "greg//chichille/virgule//bi/double",
        "fran", "fran//gast", "fran//gast//gaf",
        "fran//longtar", "fran//longtar//parcmetre"
    };

    private static void createNamespaces(MBeanServer server) throws Exception {
        final LinkedList<String> all = new LinkedList<String>();
        try {
            for (String ns : namespaces)
                all.addFirst(LocalNamespace.add(server,ns));
        } catch (Exception e) {
            removeNamespaces(server,all.toArray(new String[all.size()]));
            throw e;
        }
    }

    // Dummy test that checks that all JMXNamespaces are registered,
    // but are not returned by queryNames("*:*");
    //
    private static void checkRegistration(MBeanServer server)
        throws Exception {
        final Set<ObjectName> handlerNames = new HashSet<ObjectName>(namespaces.length);
        for (String ns : namespaces)
            handlerNames.add(JMXNamespaces.getNamespaceObjectName(ns));
        for (ObjectName nh : handlerNames) // check handler registration
            if (!server.isRegistered(nh))
                throw new InstanceNotFoundException("handler "+nh+
                        " is not registered");

        // global: queryNames("*:*") from top level
        final Set<ObjectName> all1 = server.queryNames(null,null);
        final Set<ObjectName> all2 = server.queryNames(ObjectName.WILDCARD,null);
        if (!all1.equals(all2))
            throw new Exception("queryNames(*:*) != queryNames(null)");
        final Set<ObjectName> common = new HashSet<ObjectName>(all1);
        common.retainAll(handlerNames);

        final Set<ObjectName> ref = new HashSet<ObjectName>();
        for (String ns : namespaces) {
            if (!ns.contains(JMXNamespaces.NAMESPACE_SEPARATOR))
                ref.add(JMXNamespaces.getNamespaceObjectName(ns));
        }
        if (!common.equals(ref)) {
            throw new Exception("some handler names were not returned by " +
                    "wildcard query - only returned: "+common+
                    ", expected: "+ref);
        }

        // for each namespace: queryNames("<namespace>//*:*");
        for (String ns : namespaces) {
            final ObjectName pattern = new ObjectName(ns+
                    JMXNamespaces.NAMESPACE_SEPARATOR+"*:*");
            final Set<ObjectName> all4 =
                    server.queryNames(pattern,null);
            final Set<ObjectName> common4 = new HashSet<ObjectName>(all4);
            common4.retainAll(handlerNames);

            final Set<ObjectName> ref4 = new HashSet<ObjectName>();
            for (String ns2 : namespaces) {
                if (! ns2.startsWith(ns+JMXNamespaces.NAMESPACE_SEPARATOR))
                    continue;
                if (!ns2.substring(ns.length()+
                        JMXNamespaces.NAMESPACE_SEPARATOR.length()).
                        contains(JMXNamespaces.NAMESPACE_SEPARATOR))
                    ref4.add(JMXNamespaces.getNamespaceObjectName(ns2));
            }
            if (!common4.equals(ref4)) {
                throw new Exception("some handler names were not returned by " +
                    "wildcard query on "+pattern+" - only returned: "+common4+
                    ", expected: "+ref4);
            }
        }
    }

    // Make a Map<parent, direct children>
    private static Map<String,Set<String>> makeNsTree(String[] nslist) {
        final Map<String,Set<String>> nsTree =
                new LinkedHashMap<String,Set<String>>(nslist.length);
        for (String ns : nslist) {
            if (nsTree.get(ns) == null)
                nsTree.put(ns,new LinkedHashSet<String>());
            final String[] elts = ns.split(JMXNamespaces.NAMESPACE_SEPARATOR);
            int last = ns.lastIndexOf(JMXNamespaces.NAMESPACE_SEPARATOR);
            if (last<0) continue;
            while (last > 0 && ns.charAt(last-1) == '/') last--;
            final String parent = ns.substring(0,last);
            if (nsTree.get(parent) == null)
                nsTree.put(parent,new LinkedHashSet<String>());
            nsTree.get(parent).add(ns);
        }
        return nsTree;
    }

    private static class Rigolo {
        final static String[] ones = { "a", "e", "i", "o", "u", "y", "ai", "oo",
        "ae", "ey", "ay", "oy", "au", "ou", "eu", "oi", "ei", "ea"};
        final static String[] twos = { "b", "bz", "c", "cz", "ch",
        "ct", "ck", "cs", "d", "ds", "f",  "g", "gh", "h", "j", "k", "l", "m",
        "n", "p", "ps", "q", "r", "s", "sh", "t", "v", "w", "x",
        "z"};
        final static String[] threes = {"rr","tt","pp","ss","dd","ff","ll", "mm", "nn",
        "zz", "cc", "bb"};
        final static String[] fours = {"x", "s", "ght", "cks", "rt", "rts", "ghts", "bs",
          "ts", "gg" };
        final static String[] fives = { "br", "bl", "cr", "cn", "cth", "dr",
        "fr", "fl", "cl", "chr",  "gr", "gl", "kr", "kh", "pr", "pl", "ph",
        "rh", "sr", "tr", "vr"};

        private Random rg = new Random();

        private String next(String[] table) {
            return table[rg.nextInt(table.length)];
        }

        public String nextName(int max) {
            final Random rg = new Random();
            final int nl = 3 + rg.nextInt(max);
            boolean begin = rg.nextBoolean();
            StringBuilder sb = new StringBuilder();
            for (int j = 0; j < nl ; j++) {
                if (begin) {
                    sb.append(next(ones));
                } else if (j > 0 && j < nl-1 && rg.nextInt(4)==0) {
                    sb.append(next(threes));
                } else if (j < nl-1 && rg.nextInt(3)==0) {
                    sb.append(next(fives));
                } else {
                    sb.append(next(twos));
                }
                begin = !begin;
            }
            if (!begin && rg.nextInt(2)==0)
                sb.append(next(fours));
            return sb.toString();
        }

        private ObjectName getWombatName(String ns, String domain, String name)
            throws MalformedObjectNameException {
            String d = domain;
            if (ns != null && !ns.equals(""))
                d = ns + JMXNamespaces.NAMESPACE_SEPARATOR + domain;
            return new ObjectName(d+":type=Wombat,name="+name);
        }

        public Set<ObjectName> nextWombats(String ns)
            throws MalformedObjectNameException  {
            final int dcount = 1 + rg.nextInt(5);
            final Set<ObjectName> wombats = new HashSet<ObjectName>();
            for (int i = 0; i < dcount ; i++) {
                final String d = nextName(7);
                final int ncount = 5 + rg.nextInt(20);
                for (int j = 0 ; j<ncount; j++) {
                    final String n = nextName(5);
                    wombats.add(getWombatName(ns,d,n));
                }
            }
            return wombats;
        }
    }

    public static void checkNsQuery(MBeanServer server)
        throws Exception {
        final Map<String,Set<String>> nsTree = makeNsTree(namespaces);
        final Random rg = new Random();
        final Rigolo rigolo = new Rigolo();
        for (String ns : namespaces) {
            final ObjectName name = JMXNamespaces.getNamespaceObjectName(ns);
            final String[] doms =
                    (String[])server.getAttribute(name,"Domains");
            final Set<String> subs = new HashSet<String>();
            for (String d : doms) {
                if (d.endsWith(JMXNamespaces.NAMESPACE_SEPARATOR)) {
                    subs.add(ns+JMXNamespaces.NAMESPACE_SEPARATOR+d.substring(0,
                            d.length()-JMXNamespaces.NAMESPACE_SEPARATOR.length()));
                }
            }

            final Set<String> expectNs = new HashSet<String>(nsTree.get(ns));

            if (! subs.containsAll(expectNs))
                throw new Exception("getDomains didn't return all namespaces: "+
                        "returned="+subs+", expected="+expectNs);
            if (! expectNs.containsAll(subs))
                throw new Exception("getDomains returned additional namespaces: "+
                        "returned="+subs+", expected="+expectNs);

            final Set<ObjectName> nsNames = server.queryNames(
                    new ObjectName(ns+
                    JMXNamespaces.NAMESPACE_SEPARATOR+"*"+
                    JMXNamespaces.NAMESPACE_SEPARATOR+":*"),null);

            final Set<ObjectName> expect =
                    new HashSet<ObjectName>(expectNs.size());
            for (String sub : expectNs) {
                expect.add(JMXNamespaces.getNamespaceObjectName(sub));
            }

            if (! nsNames.containsAll(expect))
                throw new Exception("queryNames didn't return all namespaces: "+
                        "returned="+nsNames+", expected="+expect);
            if (! expect.containsAll(nsNames))
                throw new Exception("getDomains returned additional namespaces: "+
                        "returned="+nsNames+", expected="+expect);

        }
    }

    private static void addWombats(MBeanServer server, Set<ObjectName> names)
        throws Exception {
        for (ObjectName on : names) {
            if (! server.isRegistered(on)) {
                server.createMBean(Wombat.class.getName(),on);
                System.out.println("A new wombat is born: "+on);
            }
        }
    }

    private static void addWombats(MBeanServer server,
             Map<String,Set<ObjectName>> wombats)
        throws Exception {
        for (String ns : wombats.keySet()) {
            addWombats(server,wombats.get(ns));
        }
    }

    private static Map<String,Set<ObjectName>> nameWombats()
        throws Exception {
        final Rigolo rigolo = new Rigolo();
        final Map<String,Set<ObjectName>> wombats =
                new HashMap<String,Set<ObjectName>>(namespaces.length);

        for (String ns : namespaces) {
            wombats.put(ns,rigolo.nextWombats(ns));
        }
        wombats.put("",rigolo.nextWombats(""));
        return wombats;
    }

    private static boolean removeWombats(MBeanServer server,
            Map<String,Set<ObjectName>> wombats) {
        boolean res = true;
        for (String ns : wombats.keySet()) {
            res = res && removeWombats(server,wombats.get(ns));
        }
        return res;
    }

    private static boolean removeWombats(MBeanServer server,
            Set<ObjectName> wombats) {
        boolean res = true;
        for (ObjectName on : wombats) {
            try {
                if (server.isRegistered(on))
                    server.unregisterMBean(on);
            } catch (Exception x) {
                res = false;
                System.out.println("Failed to remove "+on+": "+x);
            }
        }
        return res;
    }

    public static void main(String[] args)
        throws Exception {
        final MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        Map<String,Set<ObjectName>>  wombats = nameWombats();
        createNamespaces(server);
        try {
            addWombats(server,wombats);
            System.out.println("MBeans: " +server.getMBeanCount());
            System.out.println("Visible: " +server.queryNames(null,null).size());
            System.out.println("Domains: " +Arrays.asList(server.getDomains()));
            checkRegistration(server);
            checkNsQuery(server);
        } finally {
            boolean res = true;
            res = res && removeWombats(server, wombats);
            if (!res)
                throw new RuntimeException("failed to cleanup some namespaces");
        }

    }

    private static boolean removeNamespaces(MBeanServer server) {
        final List<String> l = Arrays.asList(namespaces);
        Collections.reverse(l);
        return removeNamespaces(server, l.toArray(new String[namespaces.length]));
    }

    private static boolean removeNamespaces(MBeanServer server, String[] t) {
        boolean success = true;
        for (String ns : t) {
            try {
                server.unregisterMBean(JMXNamespaces.getNamespaceObjectName(ns));
            } catch (Exception x) {
                System.out.println("failed to remove namespace: "+ ns);
                success = false;
            }
        }
        return success;
    }

}