01: /*
02: * Copyright (C) 2004 TiongHiang Lee
03: *
04: * This library is free software; you can redistribute it and/or
05: * modify it under the terms of the GNU Lesser General Public
06: * License as published by the Free Software Foundation; either
07: * version 2.1 of the License, or (at your option) any later version.
08: *
09: * This library is distributed in the hope that it will be useful,
10: * but WITHOUT ANY WARRANTY; without even the implied warranty of
11: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12: * Lesser General Public License for more details.
13: *
14: * You should have received a copy of the GNU Lesser General Public
15: * License along with this library; if not, write to the Free Software
16: * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17: *
18: * Email: thlee@onemindsoft.org
19: */
20:
21: package org.onemind.swingweb.resource;
22:
23: import java.util.HashMap;
24: import java.util.Map;
25: import org.onemind.commons.java.datastructure.BiMap;
26:
27: /**
28: * The resource cache
29: * @author TiongHiang Lee (thlee@onemindsoft.org)
30: */
31: public class ResourceCache {
32:
33: /** the bidirectional map **/
34: private BiMap _idToResource = new BiMap();
35:
36: /** the inverse **/
37: private BiMap _resourceToId = _idToResource.getInverse();
38:
39: private Map _knownResources = new HashMap();
40:
41: /** the idCounter **/
42: private int idCounter = 0;
43:
44: /**
45: * Constructor
46: */
47: public ResourceCache() {
48: }
49:
50: public String getIdForResource(Resource res) {
51: return (String) _resourceToId.get(res);
52: }
53:
54: /**
55: * Get the resource
56: * @param id the id indentify the resource
57: * @return the id
58: */
59: public Resource getResource(String id) {
60: return (Resource) _idToResource.get(id);
61: }
62:
63: /**
64: * Cache the resource and return the id.
65: * If the resource was seen before, the same id will be returned
66: * @param res the resource
67: * @return the id
68: */
69: public String cacheResource(Resource res) {
70: String id = getIdForResource(res);
71: if (id == null) {
72: id = String.valueOf(idCounter++);
73: _idToResource.put(id, res);
74: _knownResources.put(res.getId(), res);
75: }
76: return id;
77: }
78:
79: public Resource getResourceByKey(String resourceKey) {
80: return (Resource) _knownResources.get(resourceKey);
81: }
82: }
|