EventClientDelegate.java 28.8 KB
Newer Older
1
/*
X
xdono 已提交
2
 * Copyright 2007-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 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 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 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723
 * 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.  Sun designates this
 * particular file as subject to the "Classpath" exception as provided
 * by Sun in the LICENSE file that accompanied this code.
 *
 * 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.
 *
 * @since JMX 2.0
 */

package javax.management.event;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Collection;
import java.util.Collections;
import java.util.UUID;

import javax.management.InstanceNotFoundException;
import javax.management.ListenerNotFoundException;
import javax.management.Notification;
import javax.management.NotificationFilter;
import javax.management.NotificationListener;
import javax.management.ObjectName;
import javax.management.remote.NotificationResult;
import com.sun.jmx.event.EventBuffer;
import com.sun.jmx.event.LeaseManager;
import com.sun.jmx.interceptor.SingleMBeanForwarder;
import com.sun.jmx.mbeanserver.Util;
import com.sun.jmx.remote.util.ClassLogger;
import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.security.AccessControlContext;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import javax.management.DynamicMBean;
import javax.management.MBeanException;
import javax.management.MBeanPermission;
import javax.management.MBeanServer;
import javax.management.MBeanServerConnection;
import javax.management.MBeanServerDelegate;
import javax.management.MBeanServerInvocationHandler;
import javax.management.MBeanServerNotification;
import javax.management.ObjectInstance;
import javax.management.StandardMBean;
import javax.management.remote.MBeanServerForwarder;

/**
 * This is the default implementation of the MBean
 * {@link EventClientDelegateMBean}.
 */
public class EventClientDelegate implements EventClientDelegateMBean {

    private EventClientDelegate(MBeanServer server) {
        if (server == null) {
            throw new NullPointerException("Null MBeanServer.");
        }

        if (logger.traceOn()) {
            logger.trace("EventClientDelegate", "new one");
        }
        mbeanServer = server;
        eventSubscriber = EventSubscriber.getEventSubscriber(mbeanServer);
    }

    /**
     * Returns an {@code EventClientDelegate} instance for the given
     * {@code MBeanServer}.  Calling this method more than once with the same
     * {@code server} argument may return the same object or a different object
     * each time.  See {@link EventClientDelegateMBean} for an example use of
     * this method.
     *
     * @param server An MBean server instance to work with.
     * @return An {@code EventClientDelegate} instance.
     * @throws NullPointerException If {@code server} is null.
     */
    public static EventClientDelegate getEventClientDelegate(MBeanServer server) {
        EventClientDelegate delegate = null;
        synchronized(delegateMap) {
            final WeakReference wrf = delegateMap.get(server);
            delegate = (wrf == null) ? null : (EventClientDelegate)wrf.get();

            if (delegate == null) {
                delegate = new EventClientDelegate(server);
                try {
                    // TODO: this may not work with federated MBean, because
                    // the delegate will *not* emit notifications for those MBeans.
                    delegate.mbeanServer.addNotificationListener(
                            MBeanServerDelegate.DELEGATE_NAME,
                            delegate.cleanListener, null, null);
                } catch (InstanceNotFoundException e) {
                    logger.fine(
                            "getEventClientDelegate",
                            "Could not add MBeanServerDelegate listener", e);
                }
                delegateMap.put(server,
                                new WeakReference<EventClientDelegate>(delegate));
            }
        }

        return delegate;
    }

    // Logic for the MBeanServerForwarder that simulates the existence of the
    // EventClientDelegate MBean. Things are complicated by the fact that
    // there may not be anything in the chain after this forwarder when it is
    // created - the connection to a real MBeanServer might only come later.
    // Recall that there are two ways of creating a JMXConnectorServer -
    // either you specify its MBeanServer when you create it, or you specify
    // no MBeanServer and register it in an MBeanServer later. In the latter
    // case, the forwarder chain points nowhere until this registration
    // happens. Since EventClientDelegate wants to add a listener to the
    // MBeanServerDelegate, we can't create an EventClientDelegate until
    // there is an MBeanServer. So the forwarder initially has
    // a dummy ECD where every method throws an exception, and
    // the real ECD is created as soon as doing so does not produce an
    // exception.
    // TODO: rewrite so that the switch from the dummy to the real ECD happens
    // just before we would otherwise have thrown UnsupportedOperationException.
    // This is more correct, because it's not guaranteed that we will see the
    // moment where the real MBeanServer is attached, if it happens by virtue
    // of a setMBeanServer on some other forwarder later in the chain.

    private static class Forwarder extends SingleMBeanForwarder {

        private static class UnsupportedInvocationHandler
                implements InvocationHandler {
            public Object invoke(Object proxy, Method method, Object[] args)
                    throws Throwable {
                throw new UnsupportedOperationException(
                        "EventClientDelegate unavailable: no MBeanServer, or " +
                        "MBeanServer inaccessible");
            }
        }

        private static DynamicMBean makeUnsupportedECD() {
            EventClientDelegateMBean unsupported = (EventClientDelegateMBean)
                Proxy.newProxyInstance(
                    EventClientDelegateMBean.class.getClassLoader(),
                    new Class<?>[] {EventClientDelegateMBean.class},
                    new UnsupportedInvocationHandler());
            return new StandardMBean(
                unsupported, EventClientDelegateMBean.class, false);
        }

        private volatile boolean madeECD;

        Forwarder() {
            super(OBJECT_NAME, makeUnsupportedECD());
        }

        @Override
        public synchronized void setMBeanServer(final MBeanServer mbs) {
            super.setMBeanServer(mbs);

            if (!madeECD) {
                try {
                    EventClientDelegate ecd =
                        AccessController.doPrivileged(
                            new PrivilegedAction<EventClientDelegate>() {
                                public EventClientDelegate run() {
                                    return getEventClientDelegate(Forwarder.this);
                                }
                            });
                    DynamicMBean mbean = new StandardMBean(
                            ecd, EventClientDelegateMBean.class, false);
                    setSingleMBean(mbean);
                    madeECD = true;
                } catch (Exception e) {
                    // OK: assume no MBeanServer
                    logger.fine("setMBeanServer", "isRegistered", e);
                }
            }
        }
    }

    /**
     * <p>Create a new {@link MBeanServerForwarder} that simulates the existence
     * of an {@code EventClientDelegateMBean} with the {@linkplain
     * #OBJECT_NAME default name}.  This forwarder intercepts MBean requests
     * that are targeted for that MBean and handles them itself.  All other
     * requests are forwarded to the next element in the forwarder chain.</p>
     *
     * @return a new {@code MBeanServerForwarder} that simulates the existence
     * of an {@code EventClientDelegateMBean}.
     */
    public static MBeanServerForwarder newForwarder() {
        return new Forwarder();
    }

    /**
     * Returns a proxy of the default {@code EventClientDelegateMBean}.
     *
     * @param conn An {@link MBeanServerConnection} to work with.
     */
    @SuppressWarnings("cast") // cast for jdk 1.5
    public static EventClientDelegateMBean getProxy(MBeanServerConnection conn) {
        return  (EventClientDelegateMBean)MBeanServerInvocationHandler.
                newProxyInstance(conn,
                OBJECT_NAME,
                EventClientDelegateMBean.class,
                false);
    }

    public String addClient(String className, Object[] params, String[] sig)
    throws MBeanException {
        return addClient(className, null, params, sig, true);
    }

    public String addClient(String className,
            ObjectName classLoader,
            Object[] params,
            String[] sig) throws MBeanException {
        return addClient(className, classLoader, params, sig, false);
    }

    private String addClient(String className,
            ObjectName classLoader,
            Object[] params,
            String[] sig,
            boolean classLoaderRepository) throws MBeanException {
        try {
            return addClientX(
                    className, classLoader, params, sig, classLoaderRepository);
        } catch (RuntimeException e) {
            throw e;
        } catch (Exception e) {
            throw new MBeanException(e);
        }
    }

    private String addClientX(String className,
            ObjectName classLoader,
            Object[] params,
            String[] sig,
            boolean classLoaderRepository) throws Exception {
        if (className == null) {
            throw new IllegalArgumentException("Null class name.");
        }

        final Object o;

        // The special treatment of standard EventForwarders is so that no
        // special permissions are necessary to use them.  Otherwise you
        // couldn't use EventClient if you didn't have permission to call
        // MBeanServer.instantiate.  We do require that permission for
        // non-standard forwarders, because otherwise you could instantiate
        // any class with possibly adverse consequences.  We also avoid using
        // MBeanInstantiator because it looks up constructors by loading each
        // class in the sig array, which means a remote user could cause any
        // class to be loaded.  That's probably not hugely risky but still.
        if (className.startsWith("javax.management.event.")) {
            Class<?> c = Class.forName(
                    className, false, this.getClass().getClassLoader());
            Constructor<?> foundCons = null;
            if (sig == null)
                sig = new String[0];
            for (Constructor cons : c.getConstructors()) {
                Class<?>[] types = cons.getParameterTypes();
                String[] consSig = new String[types.length];
                for (int i = 0; i < types.length; i++)
                    consSig[i] = types[i].getName();
                if (Arrays.equals(sig, consSig)) {
                    foundCons = cons;
                    break;
                }
            }
            if (foundCons == null) {
                throw new NoSuchMethodException(
                        "Constructor for " + className + " with argument types " +
                        Arrays.toString(sig));
            }
            o = foundCons.newInstance(params);
        } else if (classLoaderRepository) {
            o = mbeanServer.instantiate(className, params, sig);
        } else {
            o = mbeanServer.instantiate(className, classLoader, params, sig);
        }

        if (!(o instanceof EventForwarder)) {
            throw new IllegalArgumentException(
                    className+" is not an EventForwarder class.");
        }

        final EventForwarder forwarder = (EventForwarder)o;
        final String clientId = UUID.randomUUID().toString();
        ClientInfo clientInfo = new ClientInfo(clientId, forwarder);

        clientInfoMap.put(clientId, clientInfo);

        forwarder.setClientId(clientId);

        if (logger.traceOn()) {
            logger.trace("addClient", clientId);
        }

        return clientId;
    }

    public Integer[] getListenerIds(String clientId)
    throws IOException, EventClientNotFoundException {
        ClientInfo clientInfo = getClientInfo(clientId);

        if (clientInfo == null) {
            throw new EventClientNotFoundException("The client is not found.");
        }

        Map<Integer, AddedListener> listenerInfoMap = clientInfo.listenerInfoMap;
        synchronized (listenerInfoMap) {
            Set<Integer> ids = listenerInfoMap.keySet();
            return ids.toArray(new Integer[ids.size()]);
        }
    }

    /**
     * {@inheritDoc}
     *
     * <p>The execution of this method includes a call to
     * {@link MBeanServer#addNotificationListener(ObjectName,
     * NotificationListener, NotificationFilter, Object)}.</p>
     */
    public Integer addListener(String clientId,
            final ObjectName name,
            NotificationFilter filter)
            throws EventClientNotFoundException, InstanceNotFoundException {

        if (logger.traceOn()) {
            logger.trace("addListener", "");
        }

        return getClientInfo(clientId).addListenerInfo(name, filter);
    }

    /**
     * {@inheritDoc}
     *
     * <p>The execution of this method can include call to
     * {@link MBeanServer#removeNotificationListener(ObjectName,
     * NotificationListener, NotificationFilter, Object)}.</p>
     */
    public void removeListenerOrSubscriber(String clientId, Integer listenerId)
    throws InstanceNotFoundException,
            ListenerNotFoundException,
            EventClientNotFoundException,
            IOException {
        if (logger.traceOn()) {
            logger.trace("removeListener", ""+listenerId);
        }
        getClientInfo(clientId).removeListenerInfo(listenerId);
    }

    /**
     * {@inheritDoc}
     *
     * <p>The execution of this method includes a call to
     * {@link MBeanServer#addNotificationListener(ObjectName,
     * NotificationListener, NotificationFilter, Object)} for
     * every MBean matching {@code name}.  If {@code name} is
     * an {@code ObjectName} pattern, then the execution of this
     * method will include a call to {@link MBeanServer#queryNames}.</p>
     */
    public Integer addSubscriber(String clientId, ObjectName name,
            NotificationFilter filter)
            throws EventClientNotFoundException, IOException {
        if (logger.traceOn()) {
            logger.trace("addSubscriber", "");
        }
        return getClientInfo(clientId).subscribeListenerInfo(name, filter);
    }

    public NotificationResult fetchNotifications(String clientId,
            long startSequenceNumber,
            int maxNotifs,
            long timeout)
            throws EventClientNotFoundException {
        if (logger.traceOn()) {
            logger.trace("fetchNotifications", "for "+clientId);
        }
        return getClientInfo(clientId).fetchNotifications(startSequenceNumber,
                maxNotifs,
                timeout);
    }

    public void removeClient(String clientId)
    throws EventClientNotFoundException {
        if (clientId == null)
            throw new EventClientNotFoundException("Null clientId");
        if (logger.traceOn()) {
            logger.trace("removeClient", clientId);
        }
        ClientInfo ci = null;
        ci = clientInfoMap.remove(clientId);

        if (ci == null) {
            throw new EventClientNotFoundException("clientId is "+clientId);
        } else {
            ci.clean();
        }
    }

    public long lease(String clientId, long timeout)
    throws IOException, EventClientNotFoundException {
        if (logger.traceOn()) {
            logger.trace("lease", "for "+clientId);
        }
        return getClientInfo(clientId).lease(timeout);
    }

    // ------------------------------------
    // private classes
    // ------------------------------------
    private class ClientInfo {
        String clientId;
        EventBuffer buffer;
        NotificationListener clientListener;
        Map<Integer, AddedListener> listenerInfoMap =
                new HashMap<Integer, AddedListener>();

        ClientInfo(String clientId, EventForwarder forwarder) {
            this.clientId = clientId;
            this.forwarder = forwarder;
            clientListener =
                    new ForwardingClientListener(listenerInfoMap, forwarder);
        }

        Integer addOrSubscribeListenerInfo(
                ObjectName name, NotificationFilter filter, boolean subscribe)
                throws InstanceNotFoundException, IOException {

            final Integer listenerId = nextListenerId();
            AddedListener listenerInfo = new AddedListener(
                    listenerId, filter, name, subscribe);
            if (subscribe) {
                eventSubscriber.subscribe(name,
                        clientListener,
                        filter,
                        listenerInfo);
            } else {
                mbeanServer.addNotificationListener(name,
                        clientListener,
                        filter,
                        listenerInfo);
            }

            synchronized(listenerInfoMap) {
                listenerInfoMap.put(listenerId, listenerInfo);
            }

            return listenerId;
        }

        Integer addListenerInfo(ObjectName name,
                NotificationFilter filter) throws InstanceNotFoundException {
            try {
                return addOrSubscribeListenerInfo(name, filter, false);
            } catch (IOException e) { // can't happen
                logger.warning(
                        "EventClientDelegate.addListenerInfo",
                        "unexpected exception", e);
                throw new RuntimeException(e);
            }
        }

        Integer subscribeListenerInfo(ObjectName name,
                NotificationFilter filter) throws IOException {
            try {
                return addOrSubscribeListenerInfo(name, filter, true);
            } catch (InstanceNotFoundException e) { // can't happen
                logger.warning(
                        "EventClientDelegate.subscribeListenerInfo",
                        "unexpected exception", e);
                throw new RuntimeException(e);
            }
        }

        private final AtomicInteger nextListenerId = new AtomicInteger();

        private Integer nextListenerId() {
            return nextListenerId.getAndIncrement();
        }

        NotificationResult fetchNotifications(long startSequenceNumber,
                int maxNotifs,
                long timeout) {

            if (!(forwarder instanceof FetchingEventForwarder)) {
                throw new IllegalArgumentException(
                        "This client is using Event Postal Service!");
            }

            return ((FetchingEventForwarder)forwarder).
                    fetchNotifications(startSequenceNumber,
                        maxNotifs, timeout);
        }

        void removeListenerInfo(Integer listenerId)
        throws InstanceNotFoundException, ListenerNotFoundException, IOException {
            AddedListener listenerInfo;
            synchronized(listenerInfoMap) {
                listenerInfo = listenerInfoMap.remove(listenerId);
            }

            if (listenerInfo == null) {
                throw new ListenerNotFoundException("The listener is not found.");
            }

            if (listenerInfo.subscription) {
                eventSubscriber.unsubscribe(listenerInfo.name,
                        clientListener);
            } else {
                mbeanServer.removeNotificationListener(listenerInfo.name,
                        clientListener,
                        listenerInfo.filter,
                        listenerInfo);
            }
        }

        void clean(ObjectName name) {
            synchronized(listenerInfoMap) {
                for (Map.Entry<Integer, AddedListener> entry :
                        listenerInfoMap.entrySet()) {
                    AddedListener li = entry.getValue();
                    if (name.equals(li.name)) {
                        listenerInfoMap.remove(entry.getKey());
                    }
                }
            }
        }

        void clean() {
            synchronized(listenerInfoMap) {
                for (AddedListener li : listenerInfoMap.values()) {
                    try {
                        mbeanServer.removeNotificationListener(li.name,
                                clientListener);
                    } catch (Exception e) {
                        logger.trace("ClientInfo.clean", "removeNL", e);
                    }
                }
                listenerInfoMap.clear();
            }

            try {
                forwarder.close();
            } catch (Exception e) {
                logger.trace(
                        "ClientInfo.clean", "forwarder.close", e);
            }

            if (leaseManager != null) {
                leaseManager.stop();
            }
        }

        long lease(long timeout) {
            return leaseManager.lease(timeout);
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) {
                return true;
            }

            if (o instanceof ClientInfo &&
                    clientId.equals(((ClientInfo)o).clientId)) {
                return true;
            }

            return false;
        }

        @Override
        public int hashCode() {
            return clientId.hashCode();
        }

        private EventForwarder forwarder = null;

        private final Runnable leaseExpiryCallback = new Runnable() {
            public void run() {
                try {
                    removeClient(clientId);
                } catch (Exception e) {
                    logger.trace(
                            "ClientInfo.leaseExpiryCallback", "removeClient", e);
                }
            }
        };

        private LeaseManager leaseManager = new LeaseManager(leaseExpiryCallback);
    }

    private class ForwardingClientListener implements NotificationListener {
        public ForwardingClientListener(Map<Integer, AddedListener> listenerInfoMap,
                EventForwarder forwarder) {
            this.listenerInfoMap = listenerInfoMap;
            this.forwarder = forwarder;
        }

        public void handleNotification(Notification n, Object o) {
            if (n == null || (!(o instanceof AddedListener))) {
                if (logger.traceOn()) {
                    logger.trace("ForwardingClientListener-handleNotification",
                            "received a unknown notif");
                }
                return;
            }

            AddedListener li = (AddedListener) o;

            if (checkListenerPermission(li.name,li.acc)) {
                try {
                    forwarder.forward(n, li.listenerId);
                } catch (Exception e) {
                    if (logger.traceOn()) {
                        logger.trace(
                                "ForwardingClientListener-handleNotification",
                                "forwarding failed.", e);
                    }
                }
            }
        }

        private final Map<Integer, AddedListener> listenerInfoMap;
        private final EventForwarder forwarder;
    }

    private class AddedListener {
        final int listenerId;
        final NotificationFilter filter;
        final ObjectName name;
        final boolean subscription;
        final AccessControlContext acc;

        public AddedListener(
                int listenerId,
                NotificationFilter filter,
                ObjectName name,
                boolean subscription) {
            this.listenerId = listenerId;
            this.filter = filter;
            this.name = name;
            this.subscription = subscription;
            acc = AccessController.getContext();
        }
    }

    private class CleanListener implements NotificationListener {
        public void handleNotification(Notification notification,
                Object handback) {
            if (notification instanceof MBeanServerNotification) {
                if (MBeanServerNotification.UNREGISTRATION_NOTIFICATION.equals(
                        notification.getType())) {
                    final ObjectName name =
                            ((MBeanServerNotification)notification).getMBeanName();

                    final Collection <ClientInfo> list =
                            Collections.unmodifiableCollection(clientInfoMap.values());

                    for (ClientInfo ci : list) {
                        ci.clean(name);
                    }
                }

            }
        }
    }

    // -------------------------------------------------
    // private method
    // -------------------------------------------------
    private ClientInfo getClientInfo(String clientId)
    throws EventClientNotFoundException {
        ClientInfo clientInfo = null;
        clientInfo = clientInfoMap.get(clientId);

        if (clientInfo == null) {
            throw new EventClientNotFoundException("The client is not found.");
        }

        return clientInfo;
    }

    /**
     * Explicitly check the MBeanPermission for
     * the current access control context.
     */
    private boolean checkListenerPermission(final ObjectName name,
            final AccessControlContext acc) {
        if (logger.traceOn()) {
            logger.trace("checkListenerPermission", "");
        }
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            try {
724 725 726 727
                final String serverName = getMBeanServerName();

                ObjectInstance oi = (ObjectInstance)
                    AccessController.doPrivileged(
728 729 730 731 732 733 734 735 736
                        new PrivilegedExceptionAction<Object>() {
                    public Object run()
                    throws InstanceNotFoundException {
                        return mbeanServer.getObjectInstance(name);
                    }
                });

                String classname = oi.getClassName();
                MBeanPermission perm = new MBeanPermission(
737
                        serverName,
738 739 740 741 742 743 744 745 746 747 748 749 750 751 752
                        classname,
                        null,
                        name,
                        "addNotificationListener");
                sm.checkPermission(perm, acc);
            } catch (Exception e) {
                if (logger.debugOn()) {
                    logger.debug("checkListenerPermission", "refused.", e);
                }
                return false;
            }
        }
        return true;
    }

753 754 755 756 757 758 759 760 761 762 763 764 765 766
    private String getMBeanServerName() {
        if (mbeanServerName != null) return mbeanServerName;
        else return (mbeanServerName = getMBeanServerName(mbeanServer));
    }

    private static String getMBeanServerName(final MBeanServer server) {
        final PrivilegedAction<String> action = new PrivilegedAction<String>() {
            public String run() {
                return Util.getMBeanServerSecurityName(server);
            }
        };
        return AccessController.doPrivileged(action);
    }

767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784
    // ------------------------------------
    // private variables
    // ------------------------------------
    private final MBeanServer mbeanServer;
    private volatile String mbeanServerName = null;
    private Map<String, ClientInfo> clientInfoMap =
            new ConcurrentHashMap<String, ClientInfo>();

    private final CleanListener cleanListener = new CleanListener();
    private final EventSubscriber eventSubscriber;

    private static final ClassLogger logger =
            new ClassLogger("javax.management.event", "EventClientDelegate");

    private static final
            Map<MBeanServer, WeakReference<EventClientDelegate>> delegateMap =
            new WeakHashMap<MBeanServer, WeakReference<EventClientDelegate>>();
}