001/*
002 * (C) Copyright 2006-2007 Nuxeo SA (http://nuxeo.com/) and others.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 *     http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 *
016 * Contributors:
017 *     Jean-Marc Orliaguet, Chalmers
018 *
019 * $Id$
020 */
021
022package org.nuxeo.theme.uids;
023
024import java.util.ArrayList;
025import java.util.Collection;
026import java.util.HashMap;
027import java.util.Map;
028import java.util.Random;
029
030import org.nuxeo.theme.Registrable;
031
032public final class UidManager implements Registrable {
033
034    private final Map<Integer, Identifiable> registry = new HashMap<Integer, Identifiable>();
035
036    public Object getObjectByUid(Integer uid) {
037        return registry.get(uid);
038    }
039
040    public synchronized int register(final Identifiable object) {
041        int uid = getFreeUid();
042        registry.put(uid, object);
043        object.setUid(uid);
044        return uid;
045    }
046
047    public synchronized void unregister(final Identifiable object) {
048        int uid = object.getUid();
049        registry.remove(uid);
050        object.setUid(null);
051    }
052
053    private synchronized int getFreeUid() {
054        Random generator = new Random();
055        generator.setSeed(0L);
056        int uid;
057        do {
058            uid = generator.nextInt();
059        } while (uid <= 0 || registry.containsKey(uid));
060        return uid;
061    }
062
063    public synchronized void clear() {
064        Collection<Identifiable> objects = new ArrayList<Identifiable>();
065        for (Identifiable o : registry.values()) {
066            objects.add(o);
067        }
068        for (Identifiable o : objects) {
069            unregister(o);
070        }
071        objects = null;
072        registry.clear();
073    }
074
075    public Collection<Integer> listUids() {
076        return registry.keySet();
077    }
078
079}