File: NotificationEmissionTest.java

package info (click to toggle)
openjdk-11 11.0.4%2B11-1
  • links: PTS, VCS
  • area: main
  • in suites: sid
  • size: 757,028 kB
  • sloc: java: 5,016,041; xml: 1,191,974; cpp: 934,731; ansic: 555,697; sh: 24,299; objc: 12,703; python: 3,602; asm: 3,415; makefile: 2,772; awk: 351; sed: 172; perl: 114; jsp: 24; csh: 3
file content (363 lines) | stat: -rw-r--r-- 13,557 bytes parent folder | download | duplicates (6)
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
/*
 * Copyright (c) 2005, 2015, Oracle and/or its affiliates. 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
 */

/*
 * @test
 * @bug 5106721
 * @key intermittent
 * @summary Check the emission of notifications when a Security Manager is
 * installed. Test the property "jmx.remote.x.check.notification.emission".
 * @author Luis-Miguel Alventosa
 *
 * @run clean NotificationEmissionTest
 * @run build NotificationEmissionTest
 * @run main NotificationEmissionTest 1
 * @run main NotificationEmissionTest 2
 * @run main NotificationEmissionTest 3
 * @run main NotificationEmissionTest 4
 * @run main NotificationEmissionTest 5
 */

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerFactory;
import javax.management.Notification;
import javax.management.NotificationBroadcasterSupport;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.JMXAuthenticator;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXPrincipal;
import javax.management.remote.JMXServiceURL;
import javax.security.auth.Subject;

public class NotificationEmissionTest {

    public class CustomJMXAuthenticator implements JMXAuthenticator {
        public Subject authenticate(Object credentials) {
            String role = ((String[]) credentials)[0];
            echo("Create principal with name = " + role);
            return new Subject(true,
                               Collections.singleton(new JMXPrincipal(role)),
                               Collections.EMPTY_SET,
                               Collections.EMPTY_SET);
        }
    }

    public interface NBMBean {
        public void emitNotification(int seqnum, ObjectName name);
    }

    public static class NB
        extends NotificationBroadcasterSupport
        implements NBMBean {
        public void emitNotification(int seqnum, ObjectName name) {
            if (name == null) {
                sendNotification(new Notification("nb", this, seqnum));
            } else {
                sendNotification(new Notification("nb", name, seqnum));
            }
        }
    }

    public class Listener implements NotificationListener {
        public List<Notification> notifs = new ArrayList<Notification>();
        public void handleNotification(Notification n, Object h) {
            echo("handleNotification:");
            echo("\tNotification = " + n);
            echo("\tNotification.SeqNum = " + n.getSequenceNumber());
            echo("\tHandback = " + h);
            notifs.add(n);
        }
    }

    public int checkNotifs(int size,
                           List<Notification> received,
                           List<ObjectName> expected) {
        if (received.size() != size) {
            echo("Error: expecting " + size + " notifications, got " +
                    received.size());
            return 1;
        } else {
            for (Notification n : received) {
                echo("Received notification: " + n);
                if (!n.getType().equals("nb")) {
                    echo("Notification type must be \"nb\"");
                    return 1;
                }
                ObjectName o = (ObjectName) n.getSource();
                int index = (int) n.getSequenceNumber();
                ObjectName nb = expected.get(index);
                if (!o.equals(nb)) {
                    echo("Notification source must be " + nb);
                    return 1;
                }
            }
        }
        return 0;
    }

    public int runTest(int testcase) throws Exception {
        echo("\n=-=-= Running testcase " + testcase + " =-=-=");
        switch (testcase) {
            case 1:
                return testNotificationEmissionProperty();
            case 2:
                return testNotificationEmissionPositive(false);
            case 3:
                return testNotificationEmissionNegative(false);
            case 4:
                return testNotificationEmissionPositive(true);
            case 5:
                return testNotificationEmissionNegative(true);
            default:
                echo("Invalid testcase");
                return 1;
        }
    }

    public int testNotificationEmissionProperty(boolean exception,
                                                Object propValue)
        throws Exception {
        try {
            testNotificationEmission(propValue);
            if (exception) {
                echo("Did not get expected exception for value: " + propValue);
                return 1;
            } else {
                echo("Property has been correctly set to value: " + propValue);
            }
        } catch (Exception e) {
            if (exception) {
                echo("Got expected exception for value: " + propValue);
                echo("Exception: " + e);
            } else {
                echo("Got unexpected exception for value: " + propValue);
                echo("Exception: " + e);
                return 1;
            }
        }
        return 0;
    }

    public int testNotificationEmissionProperty() throws Exception {
        int error = 0;
        error += testNotificationEmissionProperty(true, new Boolean(false));
        error += testNotificationEmissionProperty(true, new Boolean(true));
        error += testNotificationEmissionProperty(true, "dummy");
        error += testNotificationEmissionProperty(false, "false");
        error += testNotificationEmissionProperty(false, "true");
        error += testNotificationEmissionProperty(false, "FALSE");
        error += testNotificationEmissionProperty(false, "TRUE");
        return error;
    }

    public int testNotificationEmissionPositive(boolean prop) throws Exception {
        return testNotificationEmission(prop, "true", true, true);
    }

    public int testNotificationEmissionNegative(boolean prop) throws Exception {
        return testNotificationEmission(prop, "true", true, false);
    }

    public int testNotificationEmission(Object propValue) throws Exception {
        return testNotificationEmission(true, propValue, false, true);
    }

    public int testNotificationEmission(boolean prop,
                                        Object propValue,
                                        boolean sm,
                                        boolean policyPositive)
        throws Exception {

        JMXConnectorServer server = null;
        JMXConnector client = null;

        // Set policy file
        //
        String policyFile =
            System.getProperty("test.src") + File.separator +
            (policyPositive ? "policy.positive" : "policy.negative");
        echo("\nSetting policy file " + policyFile);
        System.setProperty("java.security.policy", policyFile);

        // Create a new MBeanServer
        //
        final MBeanServer mbs = MBeanServerFactory.createMBeanServer();

        try {
            // Create server environment map
            //
            final Map<String,Object> env = new HashMap<String,Object>();
            env.put("jmx.remote.authenticator", new CustomJMXAuthenticator());
            if (prop)
                env.put("jmx.remote.x.check.notification.emission", propValue);

            // Create the JMXServiceURL
            //
            final JMXServiceURL url = new JMXServiceURL("service:jmx:rmi://");

            // Create a JMXConnectorServer
            //
            server = JMXConnectorServerFactory.newJMXConnectorServer(url,
                                                                     env,
                                                                     mbs);

            // Start the JMXConnectorServer
            //
            server.start();

            // Create server environment map
            //
            final Map<String,Object> cenv = new HashMap<String,Object>();
            String[] credentials = new String[] { "role" , "password" };
            cenv.put("jmx.remote.credentials", credentials);

            // Create JMXConnector and connect to JMXConnectorServer
            //
            client = JMXConnectorFactory.connect(server.getAddress(), cenv);

            // Get non-secure MBeanServerConnection
            //
            final MBeanServerConnection mbsc =
                client.getMBeanServerConnection();

            // Create NB MBean
            //
            ObjectName nb1 = ObjectName.getInstance("domain:type=NB,name=1");
            ObjectName nb2 = ObjectName.getInstance("domain:type=NB,name=2");
            ObjectName nb3 = ObjectName.getInstance("domain:type=NB,name=3");
            mbsc.createMBean(NB.class.getName(), nb1);
            mbsc.createMBean(NB.class.getName(), nb2);
            mbsc.createMBean(NB.class.getName(), nb3);

            // Add notification listener
            //
            Listener li = new Listener();
            mbsc.addNotificationListener(nb1, li, null, null);
            mbsc.addNotificationListener(nb2, li, null, null);

            // Set security manager
            //
            if (sm) {
                echo("Setting SM");
                System.setSecurityManager(new SecurityManager());
            }

            // Invoke the "sendNotification" method
            //
            mbsc.invoke(nb1, "emitNotification",
                new Object[] {0, null},
                new String[] {"int", "javax.management.ObjectName"});
            mbsc.invoke(nb2, "emitNotification",
                new Object[] {1, null},
                new String[] {"int", "javax.management.ObjectName"});
            mbsc.invoke(nb2, "emitNotification",
                new Object[] {2, nb3},
                new String[] {"int", "javax.management.ObjectName"});

            // If the check is effective and we're using policy.negative,
            // then we should see the two notifs sent by nb2 (of which one
            // has a getSource() that is nb3), but not the notif sent by nb1.
            // Otherwise we should see all three notifs.  The check is only
            // effective if the property jmx.remote.x.check.notification.emission
            // is explicitly true and there is a security manager.
            int expectedNotifs =
                    (prop && sm && !policyPositive) ? 2 : 3;

            // Wait for notifications to be emitted
            //
            long deadline = System.currentTimeMillis() + 2000;
            while (li.notifs.size() < expectedNotifs &&
                    System.currentTimeMillis() < deadline)
                Thread.sleep(1);

            // Remove notification listener
            //
            mbsc.removeNotificationListener(nb1, li);
            mbsc.removeNotificationListener(nb2, li);

            int result = 0;
            List<ObjectName> sources = new ArrayList<ObjectName>();
            sources.add(nb1);
            sources.add(nb2);
            sources.add(nb3);

            result = checkNotifs(expectedNotifs, li.notifs, sources);
            if (result > 0) {
                echo("...SecurityManager=" + sm + "; policy=" + policyPositive);
                return result;
            }
        } finally {
            // Close the connection
            //
            if (client != null)
                client.close();

            // Stop the connector server
            //
            if (server != null)
                server.stop();

            // Release the MBeanServer
            //
            if (mbs != null)
                MBeanServerFactory.releaseMBeanServer(mbs);
        }

        return 0;
    }

    private static void echo(String message) {
        System.out.println(message);
    }

    public static void main(String[] args) throws Exception {

        echo("\n--- Check the emission of notifications " +
             "when a Security Manager is installed");

        NotificationEmissionTest net = new NotificationEmissionTest();

        int error = 0;

        error += net.runTest(Integer.parseInt(args[0]));

        if (error > 0) {
            final String msg = "\nTest FAILED! Got " + error + " error(s)";
            echo(msg);
            throw new IllegalArgumentException(msg);
        } else {
            echo("\nTest PASSED!");
        }
    }
}