ServiceLookupImpl.java 8.92 KB
Newer Older
Matt Tucker's avatar
Matt Tucker committed
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
/*
 * $RCSfile$
 * $Revision$
 * $Date$
 *
 * Copyright (C) 1999-2003 CoolServlets, Inc. All rights reserved.
 *
 * This software is the proprietary information of CoolServlets, Inc.
 * Use is subject to license terms.
 */
package org.jivesoftware.messenger.container.spi;

import org.jivesoftware.messenger.container.*;
import org.jivesoftware.messenger.container.EventListener;
import org.jivesoftware.util.LocaleUtils;
import org.jivesoftware.util.Log;
import java.util.*;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>Simple classs to track and manage service
 * registrations and respond to service lookups.</p>
 *
 * @author Iain Shigeoka
 */
public class ServiceLookupImpl implements ServiceLookup {

    private ServiceID id;
    private Map idTable = new HashMap();

    /**
     * Simple constructor
     */
    public ServiceLookupImpl() {
        id = new ServiceID();
    }

    public ServiceID getServiceID() {
        return id;
    }

    public Class[] getServiceTypes(ServiceTemplate tmpl, String prefix) {
        throw new UnsupportedOperationException();
    }

    public Object lookup(Class type) {
        ServiceTemplate tmpl = new ServiceTemplate();
        tmpl.types = new Class[]{type};
        return lookup(tmpl);
    }

    public Object lookup(ServiceTemplate tmpl) {
        Object found = null;
        try {
            matchLock.readLock().lock();

            Iterator itemItr;
            // Add all matching service IDs to the items list
            if (tmpl.serviceID == null) {
                itemItr = idTable.values().iterator();
            }
            else {
                LinkedList items = new LinkedList();
                items.add(idTable.get(tmpl.serviceID));
                itemItr = items.iterator();
            }

            // Now check each item for a match against attributes
            while (itemItr.hasNext()) {
                ServiceItem item = (ServiceItem)itemItr.next();
                if (isMatch(tmpl, item)) {
                    found = item.service;
                    break;
                }
            }
        }
        finally {
            matchLock.readLock().unlock();
        }
        return found;
    }

    private boolean isMatch(ServiceTemplate tmpl, ServiceItem item) {
        boolean isMatch = true;
        if (tmpl.attributes != null) {
            for (int i = 0; i < tmpl.attributes.length; i++) {
                boolean hasAttribute = false;
                for (int j = 0; j < item.attributes.length; j++) {
                    if (item.attributes[j].equals(tmpl.attributes[i])) {
                        hasAttribute = true;
                    }
                }
                if (!hasAttribute) {
                    isMatch = false;
                    item = null;
                }
            }
        }
        if (item != null && tmpl.types != null) {
            for (int i = 0; i < tmpl.types.length; i++) {
                if (!tmpl.types[i].isInstance(item.service)) {
                    isMatch = false;
                    item = null;
                    break;
                }
            }
        }
        return isMatch;
    }

    public ServiceMatches lookup(ServiceTemplate tmpl, int maxMatches) {
        throw new UnsupportedOperationException();
    }

    //private long eventID = 101;
    private static final long EVENT_ID = 101;
    private long sequenceID = 0;
    private ReadWriteLock matchLock = new ReentrantReadWriteLock();
    private HashMap matchMatchListeners = new HashMap();
    private HashMap matchNoMatchListeners = new HashMap();
    private HashMap noMatchMatchListeners = new HashMap();
    private HashMap listeners = new HashMap();


    public EventRegistration notifyRegister(ServiceTemplate tmpl,
                                            int transitions,
                                            EventListener listener) {
        try {
            matchLock.writeLock().lock();
            if ((transitions & TRANSITION_MATCH_MATCH) != 0) {
                matchMatchListeners.put(tmpl, listener);
            }
            if ((transitions & TRANSITION_MATCH_NOMATCH) != 0) {
                matchNoMatchListeners.put(tmpl, listener);
            }
            if ((transitions & TRANSITION_NOMATCH_MATCH) != 0) {
                noMatchMatchListeners.put(tmpl, listener);
            }
            List templates = (List)listeners.get(listener);
            if (templates == null) {
                templates = new LinkedList();
                listeners.put(listener, templates);
            }
            templates.add(tmpl);
            return new ServiceEventRegistrationImpl(this, listener, EVENT_ID, sequenceID);
        }
        finally {
            matchLock.writeLock().unlock();
        }
    }

    public ServiceRegistration register(ServiceItem item) {
        // Generate a service id if needed
        if (item.serviceID == null) {
            item.serviceID = new ServiceID();
        }

        // Register the service
        Object result = null;
        try {
            matchLock.writeLock().lock();
            result = idTable.put(item.serviceID, item);
        }
        finally {
            matchLock.writeLock().unlock();
        }

        // Handle transition notifications
        // This can trigger a nomatch-match or match-match event
        if (result == null) { // nomatch-match
            notifyTransitions(noMatchMatchListeners, TRANSITION_NOMATCH_MATCH, item);
        }
        else { // match-match
            notifyTransitions(matchMatchListeners, TRANSITION_MATCH_MATCH, item);
        }
        return new ServiceRegistrationImpl(this, item.serviceID);
    }

    private void notifyTransitions(Map listenerMap, int transition, ServiceItem item) {
        LinkedList notifyListenerList = new LinkedList();
        try {
            matchLock.readLock().lock();
            Iterator matches = listenerMap.keySet().iterator();
            while (matches.hasNext()) {
                ServiceTemplate tmpl = (ServiceTemplate)matches.next();
                EventListener listener = (EventListener)listenerMap.get(tmpl);
                if (isMatch(tmpl, item)) {
                    notifyListenerList.add(listener);
                }
            }
        }
        finally {
            matchLock.readLock().unlock();
        }
        Iterator notifyListeners = notifyListenerList.iterator();
        while (notifyListeners.hasNext()) {
            EventListener listener = (EventListener)notifyListeners.next();
            try {
                listener.notifyEvent(new ServiceEvent(this,
                        EVENT_ID,
                        sequenceID++,
                        null,
                        item,
                        id,
                        transition));
            }
            catch (UnknownEventException e) {
                Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
            }
        }
    }

    /**
     * Remove a service (only should be called by a ServiceRegistrationImpl.cancel()
     *
     * @param removeID The service id of the servce to remove
     */
    final void remove(ServiceID removeID) {
        ServiceItem item;
        // Remove registration
        try {
            matchLock.writeLock().lock();
            item = (ServiceItem)idTable.remove(removeID);
        }
        finally {
            matchLock.writeLock().unlock();
        }
        // Notify listeners
        if (item != null) {
            notifyTransitions(matchNoMatchListeners, TRANSITION_MATCH_NOMATCH, item);
        }
    }

    /**
     * <p>Remove a service event listener
     * (only should be called by ServiceEventRegistrationImpl.cancel()).</p>
     *
     * @param listener The event listener to remove
     */
    final void remove(EventListener listener) {
        try {
            matchLock.writeLock().lock();
            List templates = (List)listeners.remove(listener);
            if (templates != null) {
                Iterator templateItr = templates.iterator();
                while (templateItr.hasNext()) {
                    Object template = templateItr.next();
                    matchMatchListeners.remove(template);
                    matchNoMatchListeners.remove(template);
                    noMatchMatchListeners.remove(template);
                }
            }
        }
        finally {
            matchLock.writeLock().unlock();
        }
    }

    /**
     * Sets the attributes for an entry.
     * Only should be called by a ServiceRegistrationImpl.setAttributes()
     *
     * @param serviceID  The id of the service to modify
     * @param attributes The new attributes for that service
     */
    final void setAttributes(ServiceID serviceID, Entry[] attributes) {
        try {
            matchLock.writeLock().lock();
            ServiceItem item = (ServiceItem)idTable.get(serviceID);
            item.attributes = attributes;
        }
        finally {
            matchLock.writeLock().unlock();
        }
    }
}