001/* 002 * (C) Copyright 2006-2007 Nuxeo SAS <http://nuxeo.com> and others 003 * 004 * All rights reserved. This program and the accompanying materials 005 * are made available under the terms of the Eclipse Public License v1.0 006 * which accompanies this distribution, and is available at 007 * http://www.eclipse.org/legal/epl-v10.html 008 * 009 * Contributors: 010 * Jean-Marc Orliaguet, Chalmers 011 * 012 * $Id$ 013 */ 014 015package org.nuxeo.theme.uids; 016 017import java.util.ArrayList; 018import java.util.Collection; 019import java.util.HashMap; 020import java.util.Map; 021import java.util.Random; 022 023import org.nuxeo.theme.Registrable; 024 025public final class UidManager implements Registrable { 026 027 private final Map<Integer, Identifiable> registry = new HashMap<Integer, Identifiable>(); 028 029 public Object getObjectByUid(Integer uid) { 030 return registry.get(uid); 031 } 032 033 public synchronized int register(final Identifiable object) { 034 int uid = getFreeUid(); 035 registry.put(uid, object); 036 object.setUid(uid); 037 return uid; 038 } 039 040 public synchronized void unregister(final Identifiable object) { 041 int uid = object.getUid(); 042 registry.remove(uid); 043 object.setUid(null); 044 } 045 046 private synchronized int getFreeUid() { 047 Random generator = new Random(); 048 generator.setSeed(0L); 049 int uid; 050 do { 051 uid = generator.nextInt(); 052 } while (uid <= 0 || registry.containsKey(uid)); 053 return uid; 054 } 055 056 public synchronized void clear() { 057 Collection<Identifiable> objects = new ArrayList<Identifiable>(); 058 for (Identifiable o : registry.values()) { 059 objects.add(o); 060 } 061 for (Identifiable o : objects) { 062 unregister(o); 063 } 064 objects = null; 065 registry.clear(); 066 } 067 068 public Collection<Integer> listUids() { 069 return registry.keySet(); 070 } 071 072}