Codebase list libonemind-commons-java-java / upstream/latest
Imported Upstream version 1.5.5 gregor herrmann 11 years ago
85 changed file(s) with 9590 addition(s) and 0 deletion(s). Raw diff Collapse all Expand all
0 <?xml version="1.0" encoding="UTF-8"?>
1
2 <!--build.xml generated by maven from project.xml version 1.5.5
3 on date October 29 2006, time 1005-->
4
5 <project default="jar" name="commons-java" basedir=".">
6 <property name="defaulttargetdir" value="target">
7 </property>
8 <property name="libdir" value="target/lib">
9 </property>
10 <property name="classesdir" value="target/classes">
11 </property>
12 <property name="testclassesdir" value="target/test-classes">
13 </property>
14 <property name="testclassesdir" value="target/test-classes">
15 </property>
16 <property name="testreportdir" value="target/test-reports">
17 </property>
18 <property name="distdir" value="dist">
19 </property>
20 <property name="javadocdir" value="dist/docs/api">
21 </property>
22 <property name="final.name" value="commons-java-1.5.5">
23 </property>
24 <path id="build.classpath">
25 <fileset dir="${libdir}">
26 <include name="**/*.jar">
27 </include>
28 </fileset>
29 </path>
30 <target name="init" description="o Initializes some properties">
31 <mkdir dir="${libdir}">
32 </mkdir>
33 <condition property="noget">
34 <equals arg2="only" arg1="${build.sysclasspath}">
35 </equals>
36 </condition>
37 <!--Test if JUNIT is present in ANT classpath-->
38
39 <available property="Junit.present" classname="junit.framework.Test">
40 </available>
41 </target>
42 <target name="compile" description="o Compile the code" depends="get-deps">
43 <mkdir dir="${classesdir}">
44 </mkdir>
45 <javac destdir="${classesdir}" deprecation="true" debug="true" optimize="false" excludes="**/package.html">
46 <src>
47 <pathelement location="src/java">
48 </pathelement>
49 </src>
50 <classpath refid="build.classpath">
51 </classpath>
52 </javac>
53 </target>
54 <target name="jar" description="o Create the jar" depends="compile,test">
55 <jar jarfile="${defaulttargetdir}/${final.name}.jar" excludes="**/package.html" basedir="${classesdir}">
56 </jar>
57 </target>
58 <target name="clean" description="o Clean up the generated directories">
59 <delete dir="${defaulttargetdir}">
60 </delete>
61 <delete dir="${distdir}">
62 </delete>
63 </target>
64 <target name="dist" description="o Create a distribution" depends="jar, javadoc">
65 <mkdir dir="dist">
66 </mkdir>
67 <copy todir="dist">
68 <fileset dir="${defaulttargetdir}" includes="*.jar">
69 </fileset>
70 <fileset dir="${basedir}" includes="LICENSE*, README*">
71 </fileset>
72 </copy>
73 </target>
74 <target name="test" description="o Run the test cases" if="test.failure" depends="internal-test">
75 <fail message="There were test failures.">
76 </fail>
77 </target>
78 <target name="internal-test" if="Junit.present" depends="junit-present,compile-tests">
79 <mkdir dir="${testreportdir}">
80 </mkdir>
81 <junit dir="./" failureproperty="test.failure" printSummary="yes" fork="true" haltonerror="true">
82 <sysproperty key="basedir" value=".">
83 </sysproperty>
84 <formatter type="xml">
85 </formatter>
86 <formatter usefile="false" type="plain">
87 </formatter>
88 <classpath>
89 <path refid="build.classpath">
90 </path>
91 <pathelement path="${testclassesdir}">
92 </pathelement>
93 <pathelement path="${classesdir}">
94 </pathelement>
95 </classpath>
96 <batchtest todir="${testreportdir}">
97 <fileset dir="src/test">
98 <include name="**/*Test.java">
99 </include>
100 </fileset>
101 </batchtest>
102 </junit>
103 </target>
104 <target name="junit-present" unless="Junit.present" depends="init">
105 <echo>================================= WARNING ================================</echo>
106 <echo>Junit isn't present in your ${ANT_HOME}/lib directory. Tests not executed.</echo>
107 <echo>==========================================================================</echo>
108 </target>
109 <target name="compile-tests" if="Junit.present" depends="junit-present,compile">
110 <mkdir dir="${testclassesdir}">
111 </mkdir>
112 <javac destdir="${testclassesdir}" deprecation="true" debug="true" optimize="false" excludes="**/package.html">
113 <src>
114 <pathelement location="src/test">
115 </pathelement>
116 </src>
117 <classpath>
118 <path refid="build.classpath">
119 </path>
120 <pathelement path="${classesdir}">
121 </pathelement>
122 </classpath>
123 </javac>
124 <copy todir="${testclassesdir}">
125 <fileset dir="src/test">
126 <include name="**/*.xml">
127 </include>
128 </fileset>
129 </copy>
130 </target>
131 <target name="javadoc" description="o Generate javadoc" depends="get-deps">
132 <mkdir dir="${javadocdir}">
133 </mkdir>
134 <tstamp>
135 <format pattern="2004-yyyy" property="year">
136 </format>
137 </tstamp>
138 <property name="copyright" value="Copyright &amp;copy; 2004-2006 . All Rights Reserved.">
139 </property>
140 <property name="title" value="commons-java 1.5.5 API">
141 </property>
142 <javadoc use="true" private="true" destdir="${javadocdir}" author="true" version="true" sourcepath="src/java" packagenames="org.onemind.commons.java.*">
143 <classpath>
144 <path refid="build.classpath">
145 </path>
146 </classpath>
147 </javadoc>
148 </target>
149 <target name="get-deps" unless="noget" depends="init">
150 <!--Proxy settings works only with a JDK 1.2 and higher.-->
151
152 <setproxy>
153 </setproxy>
154 <get dest="${libdir}/servletapi-2.3.jar" usetimestamp="true" ignoreerrors="true" src="http://www.ibiblio.org/maven/servletapi/jars/servletapi-2.3.jar">
155 </get>
156 <get dest="${libdir}/commons-fileupload-1.0.jar" usetimestamp="true" ignoreerrors="true" src="http://www.ibiblio.org/maven/commons-fileupload/jars/commons-fileupload-1.0.jar">
157 </get>
158 </target>
159 <target name="install-maven">
160 <get dest="${user.home}/maven-install-latest.jar" usetimestamp="true" src="${repo}/maven/maven-install-latest.jar">
161 </get>
162 <unjar dest="${maven.home}" src="${user.home}/maven-install-latest.jar">
163 </unjar>
164 </target>
165 </project>
0 <postGoal name="xdoc:register-reports">
1 <!--
2 <attainGoal name="maven-changes-plugin:deregister"/>
3 <attainGoal name="maven-checkstyle-plugin:deregister"/>
4 <attainGoal name="maven-developer-activity-plugin:deregister"/>
5 <attainGoal name="maven-file-activity-plugin:deregister"/>
6 <attainGoal name="maven-javadoc-plugin:deregister"/>
7 <attainGoal name="maven-jdepend-plugin:deregister"/>
8 <attainGoal name="maven-junit-report-plugin:deregister"/>
9 <attainGoal name="maven-jxr-plugin:deregister"/>
10 <attainGoal name="maven-license-plugin:deregister"/>
11 <attainGoal name="maven-linkcheck-plugin:deregister"/>
12 <attainGoal name="maven-pmd-plugin:deregister"/>
13 <attainGoal name="maven-tasklist-plugin:deregister"/>
14 -->
15 <attainGoal name="maven-checkstyle-plugin:deregister"/>
16 <attainGoal name="maven-developer-activity-plugin:deregister"/>
17 <attainGoal name="maven-file-activity-plugin:deregister"/>
18 <attainGoal name="maven-changelog-plugin:deregister"/>
19 </postGoal>
0 #repository
1 maven.repo.central=
2 maven.repo.central.directory=
3 maven.repo.remote=http://www.ibiblio.org/maven,http://onemind-commons.sf.net/maven
4 maven.license.licenseFile=docs/License.txt
5 #maven.repo.remote.enabled=true
6
7 #site generation
8 maven.docs.src=xdocs
9 maven.xdoc.includeProjectDocumentation=yes
0 <project>
1 <pomVersion>1</pomVersion>
2 <name>commons-java</name>
3 <groupId>onemind-commons</groupId>
4 <artifactId>commons-java</artifactId>
5 <currentVersion>1.5.5</currentVersion>
6 <organization>OneMind</organization>
7 <inceptionYear>2004</inceptionYear>
8 <package>org.onemind.commons.java</package>
9 <logo>/images/logo.gif</logo>
10 <description>This is a common java library used to support other developments.</description>
11 <shortDescription>commons-java library</shortDescription>
12 <url>http://onemind-commons.sourceforge.net/common-java</url>
13 <issueTrackingUrl>
14 http://sourceforge.net/tracker/?group_id=114901
15 </issueTrackingUrl>
16 <siteAddress>onemind-commons.sf.net</siteAddress>
17 <siteDirectory>
18 /onemind-java
19 </siteDirectory>
20 <distributionSite>
21 http://onemind-commons.sourceforge.net
22 </distributionSite>
23 <distributionDirectory>
24 maven
25 </distributionDirectory>
26 <repository>
27 <connection>
28 scm:cvs:pserver:anonymous@cvs.sf.net:/cvsroot/onemind-commons:commons-java
29 </connection>
30 <url>
31 http://cvs.sf.net/viewcvs.py/onemind-commons
32 </url>
33 </repository>
34 <versions/>
35 <branches/>
36 <mailingLists>
37 <mailingList>
38 <name>${pom.name} Dev List</name>
39 </mailingList>
40 <mailingList>
41 <name>${pom.name} User List</name>
42 </mailingList>
43 </mailingLists>
44 <developers>
45 <developer>
46 <name>TiongHiang Lee</name>
47 <id>thlee</id>
48 <email>thlee@onemindsoft.org</email>
49 <roles/>
50 </developer>
51 </developers>
52 <dependencies>
53 <dependency>
54 <groupId>servletapi</groupId>
55 <artifactId>servletapi</artifactId>
56 <version>2.3</version>
57 <properties/>
58 </dependency>
59 <dependency>
60 <groupId>commons-fileupload</groupId>
61 <artifactId>commons-fileupload</artifactId>
62 <version>1.0</version>
63 <properties/>
64 </dependency>
65 </dependencies>
66 <build>
67 <sourceDirectory>src/java</sourceDirectory>
68 <unitTestSourceDirectory>src/test</unitTestSourceDirectory>
69 <unitTest>
70 <includes>
71 <include>**/*Test.java</include>
72 </includes>
73 <resources>
74 <resource>
75 <directory>${basedir}/src/test</directory>
76 <includes>
77 <include>**/*.xml</include>
78 </includes>
79 </resource>
80 </resources>
81 </unitTest>
82 </build>
83 <properties/>
84 </project>
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.HashMap;
23 /**
24 * A simple bi-directional map. It uses another map to store the inverse
25 * of this map. The key has to be unique in key space and the value need to
26 * be unique in the value space so that the value can be resolved to the key correctly.
27 * This class is not thread safe.
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: BiMap.java,v 1.1 2004/09/29 02:45:35 thlee Exp $ $Name: $
30 */
31 public class BiMap extends HashMap
32 {
33
34 /** the inverse **/
35 private final BiMap _inverse;
36
37 /**
38 * Constructor
39 */
40 public BiMap()
41 {
42 _inverse = new BiMap(this);
43 }
44
45 /**
46 * Constructor
47 * @param map the inverse
48 */
49 private BiMap(BiMap inverse)
50 {
51 _inverse = inverse;
52 }
53
54 /**
55 * Get the inverse bimap
56 * @return the bimap
57 */
58 public BiMap getInverse()
59 {
60 return _inverse;
61 }
62
63 /**
64 * {@inheritDoc}
65 */
66 public void clear()
67 {
68 super.clear();
69 _inverse.clear();
70 }
71
72 /**
73 * {@inheritDoc}
74 */
75 public Object put(Object key, Object value)
76 {
77 //some critical checks that ensure correctness
78 if (containsKey(key))
79 {
80 if (_inverse.containsKey(value))
81 {//make sure it is true
82 Object v = get(key);
83 boolean sameValue = (v == null) ? v == value : v.equals(value);
84 if (!sameValue)
85 {
86 throw new IllegalArgumentException("Value " + value + " exists in inverse");
87 } //else ok
88 } //else ok
89 } else
90 {
91 if (_inverse.containsKey(value))
92 {//will cause conflict
93 throw new IllegalArgumentException("Value " + value + " exists in inverse");
94 }
95 }
96 //pass the tests, do the things
97 remove(key);
98 _inverse.rawPut(value, key);
99 return rawPut(key, value);
100 }
101
102 /**
103 * Put the key value association with super.put()
104 * @param key the key
105 * @param value the value
106 */
107 private Object rawPut(Object key, Object value)
108 {
109 return super.put(key, value);
110 }
111
112 /**
113 * Remove the key
114 * @param key the key
115 * @return the value by super.remove();
116 */
117 private Object rawRemove(Object key)
118 {
119 return super.remove(key);
120 }
121
122 /**
123 * {@inheritDoc}
124 */
125 public Object remove(Object key)
126 {
127 if (containsKey(key))
128 {
129 return _inverse.rawRemove(rawRemove(key));
130 } else
131 {
132 return null;
133 }
134 }
135 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 /**
24 * Represents a set of classes. User can use isSubSetOf() to detect whether a given class is subclass of a class in the class set
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: ClassSet.java,v 1.3 2004/08/26 12:33:16 thlee Exp $ $Name: $
27 */
28 public class ClassSet
29 {
30
31 /** the classes * */
32 private HashSet _classes = new HashSet();
33
34 /**
35 * {@inheritDoc}
36 */
37 public ClassSet()
38 {
39 super();
40 }
41
42 /**
43 * {@inheritDoc}
44 */
45 public ClassSet(Collection c)
46 {
47 addAll(c);
48 }
49
50 /**
51 * Add all in the classes to the ClassSet
52 * @param classes the collection containing the classes
53 */
54 public void addAll(Collection classes)
55 {
56 Iterator it = classes.iterator();
57 while (it.hasNext())
58 {
59 Object o = it.next();
60 if (o instanceof Class)
61 {
62 add((Class) o);
63 } else
64 {
65 throw new IllegalArgumentException(o + " is not a subclass of class");
66 }
67 }
68 }
69
70 /**
71 * Add the class
72 * @param c the class
73 */
74 public void add(Class c)
75 {
76 _classes.add(c);
77 }
78
79 /**
80 * Check whether the class is subclass of one of the class in the class set
81 * @param c the class
82 * @return true if is subclass
83 */
84 public boolean isSubclassOfClasses(Class c)
85 {
86 Class current = c;
87 while ((current != null) && (current != Object.class))
88 {
89 if (_classes.contains(c))
90 {
91 return true;
92 } else
93 {
94 current = current.getSuperclass();
95 }
96 }
97 Class[] interfaces = c.getInterfaces();
98 for (int i = 0; i < interfaces.length; i++)
99 {
100 if (_classes.contains(interfaces[i]))
101 {
102 return true;
103 }
104 }
105 return false;
106 }
107
108 /**
109 * Get the classes
110 * @return the classes
111 */
112 public Set getClasses()
113 {
114 return _classes;
115 }
116 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 /**
24 * Represent a list of counters with a queue per counter objectYou can queue and dequeue to a counter identified by a counter object.
25 * NOTE: This class is not thread-safe
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: CounterQueue.java,v 1.3 2005/04/26 17:41:24 thlee Exp $ $Name: $
28 */
29 public class CounterQueue
30 {
31
32 /** the counters * */
33 private HashMap _counters = new HashMap();
34
35 /**
36 * {@inheritDoc}
37 */
38 public CounterQueue()
39 {
40 }
41
42 /**
43 * Get the list for the counter object
44 * @param o the counter object
45 * @return the list, or null if there's none
46 */
47 private List _getList(Object o)
48 {
49 if (_counters.containsKey(o))
50 {
51 return (List) _counters.get(o);
52 } else
53 {
54 return null;
55 }
56 }
57
58 /**
59 * Get the (unmodifiable) queue of the counter object
60 * @param o the counter object
61 * @return the queue
62 */
63 public List getQueue(Object o)
64 {
65 if (_counters.containsKey(o))
66 {
67 return Collections.unmodifiableList((List) _counters.get(o));
68 } else
69 {
70 return Collections.EMPTY_LIST;
71 }
72 }
73
74 /**
75 * Clear the queue of the counter object
76 * @param o the counter object
77 * @return the queue for the counter object
78 */
79 public List clearQueue(Object o)
80 {
81 Object queue = _counters.remove(o);
82 if (queue != null)
83 {
84 return (List) queue;
85 } else
86 {
87 return Collections.EMPTY_LIST;
88 }
89 }
90
91 /**
92 * Add an queuer to the queue of the counter object. A queue will be created if there's none for the counter object
93 * @param o the counter object
94 * @param queuer the queue
95 * @return true
96 */
97 public boolean addToQueue(Object o, Object queuer)
98 {
99 List l = _getList(o);
100 if (l == null)
101 {
102 l = new ArrayList();
103 _counters.put(o, l);
104 }
105 return l.add(queuer);
106 }
107
108 /**
109 * Remove the next queuer in the queue. Null if queue is empty
110 * @param counter the counter
111 * @return the next queuer in the counter, or null if queue is empty
112 */
113 public Object removeNextFromQueue(Object counter)
114 {
115 List l = _getList(counter);
116 if (l == null || l.size() == 0)
117 {
118 return null;
119 } else
120 {
121 return l.remove(0);
122 }
123 }
124
125 /**
126 * Remove the queuer from the queue of the counter object. If there's no queue for the counter object, it will do nothing and
127 * return false.
128 * @param o the counter object
129 * @param queuer the queuer
130 * @return true if list contains the element
131 */
132 public boolean removeFromQueue(Object o, Object queuer)
133 {
134 List l = _getList(o);
135 if (l != null)
136 {
137 return l.remove(queuer);
138 } else
139 {
140 return false;
141 }
142 }
143 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 /**
23 * Represent a map key that consists of two value
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 */
26 public class DuoMapKey
27 {
28
29 private final int _hashCode;
30
31 /** key1 **/
32 private Object key1;
33
34 /** key2 **/
35 private Object key2;
36
37 /**
38 * Constructor
39 * @param key1
40 * @param key2
41 */
42 public DuoMapKey(Object key1, Object key2)
43 {
44 _hashCode = ((key1 == null) ? 0 : key1.hashCode()) + ((key2 == null) ? 0 : key2.hashCode() >> 4);
45 }
46
47 /**
48 * {@inheritDoc}
49 */
50 public int hashCode()
51 {
52 return _hashCode;
53 }
54
55 /**
56 * {@inheritDoc}
57 */
58 public boolean equals(Object o)
59 {
60 if (o instanceof DuoMapKey)
61 {
62 DuoMapKey other = (DuoMapKey) o;
63 return _keyEquals(key1, other.key1) && _keyEquals(key2, other.key2);
64 } else
65 {
66 return false;
67 }
68 }
69
70 /**
71 * Return whether key and other is equals
72 * @param key the key
73 * @param other the other key
74 * @return true if both null or equals
75 */
76 private boolean _keyEquals(Object key, Object other)
77 {
78 if (key == null)
79 {
80 return other == null;
81 } else
82 {
83 return key.equals(other);
84 }
85 }
86 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 /**
24 * Associate a class and an value object and resolve the mapping through the
25 * class hierachy.
26 *
27 * For example, if a value object A is assosiated with Number class that
28 * means it is associated with the Number class and all the subclasses of
29 * object class. However, if a mapping exists for Integer, the InheritableValueMap
30 * will return the value object associated for the Integer.
31 *
32 * The stopClass controls when the InheritableValueMap stop resolving mapping and
33 * return null (when c==stopClass.getSuperClass()). The stopClass also control
34 * the hierachy of object that can be added the the map - meaning
35 * stopClass.isAssignableFrom(c) must evaluate to true when c is added as mapping key.
36 *
37 * @author TiongHiang Lee (thlee@onemindsoft.org)
38 * @version $Id: InheritableValueMap.java,v 1.3 2005/02/17 19:57:31 thlee Exp $ $Name: $
39 */
40 public class InheritableValueMap
41 {
42
43 /** the mapping * */
44 private Map _map = new HashMap();
45
46 /** the stop class * */
47 private Class _stopClass;
48
49 /**
50 * Use Object.class as stop class {@inheritDoc}
51 */
52 public InheritableValueMap()
53 {
54 this(Object.class);
55 }
56
57 /**
58 * {@inheritDoc}
59 * @param stopClass the stop class
60 */
61 public InheritableValueMap(Class stopClass)
62 {
63 _stopClass = stopClass;
64 }
65
66 /**
67 * Add the mapping between the class c and the object o. The object o must be the stopClass or a subclass of the stopClass
68 * @param c the class
69 * @param o the object
70 */
71 public void put(Class c, Object o)
72 {
73 if (!_stopClass.isAssignableFrom(c))
74 {
75 throw new IllegalArgumentException("Cannot add key class " + c
76 + " that is not a subclass of stopClass " + _stopClass);
77 }
78 _map.put(c, o);
79 }
80
81 /**
82 * Resolve the object associated with class c
83 * @param c the class
84 * @return the object associated with class c, or null
85 */
86 public Object resolve(Class c)
87 {
88 if (c == null)
89 { //add protection
90 return null;
91 } else if (!_stopClass.isAssignableFrom(c))
92 {
93 throw new RuntimeException(
94 "Cannot get entry for key class that is not a subclass of stopClass "
95 + _stopClass);
96 }
97 while (c != _stopClass.getSuperclass())
98 {
99 Object o = _map.get(c);
100 if (o != null)
101 {
102 return o;
103 }
104 c = c.getSuperclass();
105 }
106 return null;
107 }
108
109 /**
110 * Return the key classes
111 * @return the classes
112 */
113 public final Set keySet()
114 {
115 return _map.keySet();
116 }
117
118 /**
119 * Resolve all the mapping that could have apply to c in class c's inheritance hierachy
120 * @param c the class
121 * @return the Collection contains all the mappings
122 */
123 public Collection resolveAll(Class c)
124 {
125 if (!_stopClass.isAssignableFrom(c))
126 {
127 throw new RuntimeException(
128 "Cannot get entry for key class that is not a subclass of stopClass "
129 + _stopClass);
130 }
131 List l = new ArrayList();
132 while (c != _stopClass.getSuperclass())
133 {
134 Object o = _map.get(c);
135 if (o != null)
136 {
137 l.add(o);
138 }
139 c = c.getSuperclass();
140 }
141 return l;
142 }
143 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 /**
23 * Represents a list of long
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: LongList.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
26 */
27 public class LongList
28 {
29
30 /** the initial capacity * */
31 private static final int INITIAL_CAPACITY = 10;
32
33 /** the growth rate * */
34 private static final int GROW = 10;
35
36 /** the count of longs in the list * */
37 private int _count;
38
39 /** the list * */
40 private long[] _list = new long[INITIAL_CAPACITY];
41
42 /**
43 * {@inheritDoc}
44 */
45 public LongList()
46 {
47 this(INITIAL_CAPACITY);
48 }
49
50 /**
51 * {@inheritDoc}
52 * @param capacity initial capacity
53 */
54 public LongList(int capacity)
55 {
56 _list = new long[INITIAL_CAPACITY];
57 }
58
59 /**
60 * Add a long to the list
61 * @param l the long
62 */
63 public void add(long l)
64 {
65 ensureCapacity(_count + 1);
66 _list[_count] = l;
67 _count++;
68 }
69
70 /**
71 * Get the long on index i in the list
72 * @param i the index
73 * @return the long
74 */
75 public long get(int i)
76 {
77 if ((i < 0) || (i >= _count))
78 {
79 throw new IndexOutOfBoundsException("Invalid index " + i);
80 } else
81 {
82 return _list[i];
83 }
84 }
85
86 /**
87 * Add a long at index i
88 * @param l the long
89 * @param i the index
90 */
91 public void add(long l, int i)
92 {
93 if ((i < 0) || (i > _count))
94 {
95 throw new IndexOutOfBoundsException("Invalid index " + i);
96 } else if (i == _count)
97 {
98 add(l);
99 } else
100 {
101 ensureCapacity(_count + 1);
102 for (int j = _count; j > i; j--)
103 {
104 _list[j] = _list[j - 1];
105 }
106 _count++;
107 _list[i] = l;
108 }
109 }
110
111 /**
112 * ensure the capacity of the long
113 * @param size the size
114 */
115 private void ensureCapacity(int size)
116 {
117 if (_list.length < size)
118 {
119 long[] newlist = new long[_list.length + GROW];
120 for (int i = 0; i < _list.length; i++)
121 {
122 newlist[i] = _list[i];
123 }
124 _list = newlist;
125 }
126 }
127
128 /**
129 * Remove the long at index i
130 * @param i the index
131 * @return the long at index i
132 */
133 public long remove(int i)
134 {
135 if ((i < 0) || (i >= _count))
136 {
137 throw new IndexOutOfBoundsException("Invalid index " + i);
138 } else
139 {
140 long save = _list[i];
141 for (int j = i; j < (_count - 2); j--)
142 {
143 _list[j] = _list[j + 1];
144 }
145 _count--;
146 return save;
147 }
148 }
149
150 /**
151 * Return the first long in the list
152 * @return the first long
153 */
154 public long first()
155 {
156 return _list[0];
157 }
158
159 /**
160 * Return the last long in the list
161 * @return the last long
162 */
163 public long last()
164 {
165 return _list[_count - 1];
166 }
167 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25 /**
26 * A lookup cache implements simple lookup caching algorithm for looking up things. The derived class simply implement the
27 * produce(Object key) method which is assumed an expensive operation and the results will be cached by the lookup cache
28 * implementation. There's no public method on lookup cache, the developer should provide application specific lookup interface.
29 * @author TiongHiang Lee (thlee@onemindsoft.org)
30 * @version $Id: LookupCache.java,v 1.4 2004/09/30 13:26:26 thlee Exp $ $Name: $
31 */
32 public abstract class LookupCache
33 {
34
35 /** the logger * */
36 private static final Logger _logger = Logger.getLogger(LookupCache.class.getName());
37
38 /** the hit cache * */
39 private Map _cache = new HashMap();
40
41 /** the negative cache * */
42 private Set _negCache;
43
44 /** indicate whether to do negative caching * */
45 private boolean _doNegCache = true;
46
47 /**
48 * {@inheritDoc}
49 */
50 public LookupCache()
51 {
52 this(true);
53 }
54
55 /**
56 * {@inheritDoc}
57 * @param doNegCache whether to do negative caching
58 */
59 public LookupCache(boolean doNegCache)
60 {
61 setDoNegativeCache(doNegCache);
62 }
63
64 /**
65 * The main lookup method. The developer should provide another application specific method that call this method to return what
66 * the application wants
67 * @param key the key
68 * @return the object or null
69 * @todo add synchronization when lookup the same key to avoid double loading
70 */
71 protected final Object lookup(Object key)
72 {
73 if (_doNegCache)
74 {
75 if (_negCache.contains(key))
76 {
77 if (_logger.isLoggable(Level.FINEST))
78 {
79 _logger.finest("Returning negative cache hit");
80 }
81 return null;
82 }
83 }
84 Object o = _cache.get(key);
85 if (o == null)
86 {
87 //TODO: synchronization for looking up same key
88 o = produce(key);
89 if (o != null)
90 {
91 if (_logger.isLoggable(Level.FINEST))
92 {
93 _logger.finest("Put hit of " + key + " to cache");
94 }
95 _cache.put(key, o);
96 } else
97 {
98 if (_doNegCache)
99 {
100 _logger.finest("Put negative hit of " + key + " to cache");
101 _negCache.add(key);
102 }
103 }
104 } else
105 {
106 if (_logger.isLoggable(Level.FINEST))
107 {
108 _logger.finest("Returning positive cache hit of " + key);
109 }
110 }
111 return o;
112 }
113
114 /**
115 * Produce the object given the key. This is assumed to be an expensive operation and it will be called by the lookup method.
116 * The result will be cached by the lookup method and negative result also will be cached to if the doNegCache is turned on.
117 * @param key the key
118 * @return the result or null if no result
119 */
120 protected abstract Object produce(Object key);
121
122 /**
123 * Turn on/off the negative cache
124 * @param b true to turn on the neg cache
125 */
126 protected void setDoNegativeCache(boolean b)
127 {
128 _doNegCache = b;
129 if (b && (_negCache == null))
130 {
131 _negCache = new HashSet();
132 }
133 }
134
135 /**
136 * Get whether the object is in negative cache
137 * @param o the object
138 * @return true if is in negative cache
139 */
140 protected boolean isInNegCache(Object o)
141 {
142 return _negCache.contains(o);
143 }
144
145 /**
146 * Test if the key is in cache
147 * @param o the object
148 * @return true if is in cache
149 */
150 protected boolean isInCache(Object o)
151 {
152 return _cache.containsKey(o);
153 }
154
155 /**
156 * Clear all the negative cache
157 */
158 protected void clearNegCache()
159 {
160 if (_negCache != null)
161 {
162 _negCache.clear();
163 }
164 }
165 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.Map;
23 /**
24 * A simple Map.Entry implementation that can be used for Map extension
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: MapEntry.java,v 1.3 2005/04/26 17:41:48 thlee Exp $ $Name: $
27 */
28 public class MapEntry implements Map.Entry
29 {
30
31 /** the key * */
32 private Object _key;
33
34 /** the value * */
35 private Object _value;
36
37 /**
38 * {@inheritDoc}
39 */
40 public MapEntry(Object key, Object value)
41 {
42 _key = key;
43 _value = value;
44 }
45
46 /**
47 * {@inheritDoc}
48 */
49 public Object getKey()
50 {
51 return _key;
52 }
53
54 /**
55 * {@inheritDoc}
56 */
57 public Object getValue()
58 {
59 return _value;
60 }
61
62 /**
63 * {@inheritDoc}
64 */
65 public Object setValue(Object value)
66 {
67 Object o = _value;
68 _value = value;
69 return o;
70 }
71
72 /**
73 * {@inheritDoc}
74 */
75 public int hashCode()
76 {
77 return _key.hashCode();
78 }
79
80 /**
81 * {@inheritDoc}
82 */
83 public boolean equals(Object o)
84 {
85 return _key.equals(((MapEntry) o)._key);
86 }
87 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 /**
24 * Most recently used list implementation. It support entries expiration
25 * by access time.
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: MruList.java,v 1.4 2005/04/26 17:41:59 thlee Exp $ $Name: $
28 */
29 public class MruList implements Set
30 {
31
32 /**
33 * Represent an entry in the MruList
34 * @author TiongHiang Lee
35 */
36 protected static class MruEntry implements Comparable
37 {
38
39 /** the last access time * */
40 private long _lastAccessTime;
41
42 /** the object * */
43 private Object _obj;
44
45 /**
46 * Constructor
47 * @param obj the object
48 * @param time the time
49 */
50 public MruEntry(Object obj, long time)
51 {
52 _obj = obj;
53 _lastAccessTime = time;
54 }
55
56 /**
57 * Compare by the access time
58 * @param e another entry
59 * @return a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the
60 * specified object.
61 */
62 public int compareTo(MruEntry e)
63 {
64 if (_lastAccessTime > e._lastAccessTime)
65 {
66 return -1;
67 } else if (_lastAccessTime < e._lastAccessTime)
68 {
69 return 1;
70 } else
71 {
72 if (_obj.equals(e._obj))
73 {
74 return 0;
75 } else if (_obj.hashCode() > e._obj.hashCode())
76 {
77 return 1;
78 } else
79 {
80 return -1;
81 }
82 }
83 }
84
85 /**
86 * {@inheritDoc}
87 */
88 public int compareTo(Object o)
89 {
90 return compareTo((MruEntry) o);
91 }
92
93 /**
94 * Return the lastAccessTime
95 * @return the lastAccessTime.
96 */
97 public final long getLastAccessTime()
98 {
99 return _lastAccessTime;
100 }
101
102 /**
103 * Set the lastAccessTime
104 * @param lastAccessTime The lastAccessTime to set.
105 */
106 public final void setLastAccessTime(long lastAccessTime)
107 {
108 _lastAccessTime = lastAccessTime;
109 }
110
111 /**
112 * Return the obj
113 * @return the obj.
114 */
115 public final Object getObj()
116 {
117 return _obj;
118 }
119
120 /**
121 * Set the obj
122 * @param obj The obj to set.
123 */
124 public final void setObj(Object obj)
125 {
126 _obj = obj;
127 }
128
129 /**
130 * {@inheritDoc}
131 */
132 public String toString()
133 {
134 return (_obj + ": " + _lastAccessTime);
135 }
136 }
137
138 /**
139 * An iterator to the entries
140 * @author TiongHiang Lee
141 */
142 protected static class MruIterator implements Iterator
143 {
144
145 /** the iterator * */
146 private Iterator _entryIterator;
147
148 /**
149 * Constructor
150 * @param entryIterator the iterator
151 */
152 public MruIterator(Iterator entryIterator)
153 {
154 _entryIterator = entryIterator;
155 }
156
157 /**
158 * {@inheritDoc}
159 */
160 public boolean hasNext()
161 {
162 return _entryIterator.hasNext();
163 }
164
165 /**
166 * {@inheritDoc}
167 */
168 public Object next()
169 {
170 MruEntry entry = (MruEntry) _entryIterator.next();
171 return entry._obj;
172 }
173
174 /**
175 * {@inheritDoc}
176 */
177 public void remove()
178 {
179 _entryIterator.remove();
180 }
181 }
182
183 /** the entries map * */
184 private HashMap _entryMap = new HashMap();
185
186 /** the last cleanup time * */
187 private long _lastCleanupTime;
188
189 /** the sorted mru list * */
190 private TreeSet _mruList = new TreeSet();
191
192 /** the size * */
193 private long _sizeLimit;
194
195 /** the timeout * */
196 private long _timeout;
197
198 /**
199 * {@inheritDoc}
200 */
201 public MruList()
202 {
203 this(0, 0);
204 }
205
206 /**
207 * {@inheritDoc}
208 * @param sizeLimit the size limit of the MruList (0 for no size limit)
209 * @param timeout the timeout (0 for never timeout)
210 */
211 public MruList(long sizeLimit, long timeout)
212 {
213 _sizeLimit = sizeLimit;
214 _timeout = timeout;
215 _lastCleanupTime = System.currentTimeMillis();
216 }
217
218 /**
219 * Record that object o is being accessed. This will put a timestamp to the object
220 * @param o the object
221 * @return true if the object was in the list before
222 */
223 public boolean access(Object o)
224 {
225 long now = System.currentTimeMillis();
226 if ((_timeout > 0) && ((now - _lastCleanupTime) > _timeout))
227 {
228 expireEntries(_timeout);
229 }
230 boolean flag = false;
231 MruEntry entry = (MruEntry) _entryMap.get(o);
232 if (entry != null)
233 { //exist already
234 _mruList.remove(entry);//must remove to add again later
235 entry._lastAccessTime = now;
236 flag = true;
237 } else
238 {
239 entry = new MruEntry(o, now);
240 _entryMap.put(o, entry);
241 }
242 _mruList.add(entry);
243 if ((_sizeLimit > 0) && (size() > _sizeLimit))
244 {
245 truncateEntries(_sizeLimit);
246 }
247 return flag;
248 }
249
250 /**
251 * @see access(Object o)
252 */
253 public boolean add(Object o)
254 {
255 return access(o);
256 }
257
258 /**
259 * {@inheritDoc}
260 */
261 public boolean addAll(Collection c)
262 {
263 Iterator it = c.iterator();
264 while (it.hasNext())
265 {
266 add(it.next());
267 }
268 return true;
269 }
270
271 /**
272 * {@inheritDoc}
273 */
274 public void clear()
275 {
276 _entryMap.clear();
277 _mruList.clear();
278 }
279
280 /**
281 * {@inheritDoc}
282 */
283 public boolean contains(Object o)
284 {
285 return _entryMap.containsKey(o);
286 }
287
288 /**
289 * {@inheritDoc}
290 */
291 public boolean containsAll(Collection c)
292 {
293 return _entryMap.keySet().containsAll(c);
294 }
295
296 /**
297 * Expire the entries that was last access longer that time t Document this method.
298 * @param t the elapse time
299 */
300 public void expireEntries(long t)
301 {
302 long now = System.currentTimeMillis();
303 _lastCleanupTime = now;
304 do
305 {
306 MruEntry entry = (MruEntry) _mruList.last();
307 if (entry == null)
308 {
309 break;
310 } else if ((now - entry._lastAccessTime) > t)
311 {
312 expireEntry(entry._obj);
313 } else
314 {
315 break;
316 }
317 } while (true);
318 }
319
320 /**
321 * Get the last access time object obj
322 * @param obj the object
323 * @return the access time, or -1 if the object is not in the cache
324 */
325 public long getLastAccessTime(Object obj)
326 {
327 MruEntry entry = (MruEntry) _entryMap.get(obj);
328 if (entry != null)
329 {
330 return entry._lastAccessTime;
331 } else
332 {
333 return -1;
334 }
335 }
336
337 /**
338 * {@inheritDoc}
339 */
340 public boolean isEmpty()
341 {
342 return _entryMap.size() == 0;
343 }
344
345 /**
346 * {@inheritDoc}
347 */
348 public Iterator iterator()
349 {
350 return new MruIterator(_mruList.iterator());
351 }
352
353 /**
354 * {@inheritDoc}
355 */
356 public boolean remove(Object o)
357 {
358 MruEntry entry = (MruEntry) _entryMap.remove(o);
359 boolean flag = false;
360 if (entry != null)
361 {
362 _mruList.remove(entry);
363 flag = true;
364 }
365 return flag;
366 }
367
368 /**
369 * {@inheritDoc}
370 */
371 public boolean removeAll(Collection c)
372 {
373 boolean flag = false;
374 Iterator it = c.iterator();
375 while (it.hasNext())
376 {
377 if (remove(it.next()))
378 {
379 flag = true;
380 }
381 }
382 return flag;
383 }
384
385 /**
386 * {@inheritDoc}
387 */
388 public boolean retainAll(Collection c)
389 {
390 Iterator it = _entryMap.keySet().iterator();
391 boolean flag = false;
392 while (it.hasNext())
393 {
394 Object obj = it.next();
395 if (!c.contains(obj))
396 {
397 remove(obj);
398 flag = true;
399 }
400 }
401 return flag;
402 }
403
404 /**
405 * {@inheritDoc}
406 */
407 public int size()
408 {
409 return _entryMap.size();
410 }
411
412 /**
413 * {@inheritDoc}
414 */
415 public Object[] toArray()
416 {
417 throw new UnsupportedOperationException("Not implemented");
418 }
419
420 /**
421 * {@inheritDoc}
422 */
423 public Object[] toArray(Object[] a)
424 {
425 throw new UnsupportedOperationException("Not implemented");
426 }
427
428 /**
429 * Truncate the entries to specific size
430 * @param size the size
431 */
432 public void truncateEntries(long size)
433 {
434 while (size() > size)
435 {
436 MruEntry entry = (MruEntry) _mruList.last();
437 truncateEntry(entry._obj);
438 }
439 }
440
441 /**
442 * Remove the object from the MruList
443 * @param obj the object
444 */
445 protected void truncateEntry(Object obj)
446 {
447 remove(obj);
448 }
449
450 /**
451 * Remove the entry from the MruList
452 * @param obj expire the entry
453 */
454 protected void expireEntry(Object obj)
455 {
456 remove(obj);
457 }
458 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 /**
24 * Most recently used map (implementation based on mrulist)
25 *
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: MruMap.java,v 1.3 2004/10/31 15:57:55 thlee Exp $ $Name: $
28 */
29 public class MruMap extends HashMap implements Map
30 {
31
32 /**
33 * For MruMap implementation
34 * @author TiongHiang Lee (thlee@onemindsoft.org)
35 * @version $Id: MruMap.java,v 1.3 2004/10/31 15:57:55 thlee Exp $ $Name: $
36 */
37 private class InnerMruList extends MruList
38 {
39 /**
40 * Constructor
41 * @param size the size
42 * @param timeout the timeout
43 */
44 public InnerMruList(long size, long timeout)
45 {
46 super(size, timeout);
47 }
48
49 /**
50 * {@inheritDoc}
51 */
52 protected void truncateEntry(Object obj)
53 {
54 super.truncateEntry(obj);
55 MruMap.this.remove(obj);
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 protected void expireEntry(Object obj)
62 {
63 super.expireEntry(obj);
64 MruMap.this.remove(obj);
65 }
66 }
67
68 /** the list * */
69 private MruList _mruList;
70
71 /**
72 * {@inheritDoc}
73 */
74 public MruMap()
75 {
76 this(0, 0);
77 }
78
79 /**
80 * Constructor
81 * @param size the limit of the map (0 for never timeout)
82 * @param timeout the timeout (0 for never expire)
83 */
84 public MruMap(long size, long timeout)
85 {
86 _mruList = new InnerMruList(size, timeout);
87 }
88
89 /**
90 * {@inheritDoc}
91 */
92 public void clear()
93 {
94 super.clear();
95 _mruList.clear();
96 }
97
98 /**
99 * {@inheritDoc}
100 */
101 public Object get(Object key)
102 {
103 _mruList.access(key);
104 return super.get(key);
105 }
106
107 /**
108 * {@inheritDoc}
109 */
110 public Object put(Object key, Object value)
111 {
112 Object result = super.put(key, value);
113 _mruList.access(key); //this must be done second
114 return result;
115 }
116
117 /**
118 * {@inheritDoc}
119 */
120 public void putAll(Map t)
121 {
122 super.putAll(t);//this must be done second
123 _mruList.addAll(t.keySet());
124
125 }
126
127 /**
128 * {@inheritDoc}
129 */
130 public Object remove(Object key)
131 {
132 _mruList.remove(key);
133 return super.remove(key);
134 }
135
136 /**
137 * {@inheritDoc}
138 */
139 public void expire(MruList list, Object obj)
140 {
141 super.remove(obj);
142 }
143
144 /**
145 * {@inheritDoc}
146 */
147 public void truncate(MruList list, Object obj)
148 {
149 super.remove(obj);
150 }
151 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.Map;
23
24 /**
25 * A name table interface
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 */
28 public interface Nametable
29 {
30
31 /**
32 * Declare a variable in the name table
33 * @param name the name
34 * @param value the value
35 */
36 void declare(String name, Object value);
37
38 /**
39 * Assign a variable in the name table
40 * @param name the name
41 * @param value the value
42 * @return the old value, or null
43 */
44 Object assign(String name, Object value);
45
46 /**
47 * Whether the nametable contains the name
48 * @param name the name
49 * @return true if contains the name
50 */
51 boolean containsName(String name);
52
53 /**
54 * Access the value associated with name
55 * @param name
56 * @return
57 */
58 Object access(String name);
59
60 /**
61 * Undeclare the name
62 * @param name
63 */
64 void undeclare(String name);
65
66 /**
67 * Return map representation of this nametable
68 * @return unmodifiable map representation of this nametable
69 */
70 Map asMap();
71 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 import java.util.logging.Logger;
24 /**
25 * A nametable stack contains key-value mapping that has a scope.
26 * A new scope can be opened for putting new mappings and all the
27 * mappings added in this scope can be wiped out easily with a
28 * closeScope command. In effect this is like a stack of Maps,
29 * hence the name NametableStack.
30 *
31 * NOTE: the implementation use a map and list to achieve the behaviour.
32 * @author TiongHiang Lee (thlee@onemindsoft.org)
33 * @version $Id: NametableStack.java,v 1.7 2005/06/22 22:57:37 thlee Exp $ $Name: $
34 */
35 public class NametableStack
36 {
37
38 /** the logger * */
39 private static final Logger _logger = Logger.getLogger(NametableStack.class.getName());
40
41 /** the map * */
42 private Nametable _nametable;
43
44 /** the list of maps * */
45 private ArrayList _list = new ArrayList();
46
47 /**
48 * The local nametable defines a scope where local variables mask out the global
49 * variables, but the global variable can still be accessed. This is useful for
50 * implementing function context
51 *
52 * @author TiongHiang Lee (thlee@onemindsoft.org)
53 */
54 private static class LocalNametable implements Nametable
55 {
56
57 /** the local variables **/
58 private final Map _locals = new HashMap();
59
60 /** the global map **/
61 private final Nametable _global;
62
63 /** the scope **/
64 private final int _scope;
65
66 /**
67 * Constructor
68 * @param global the global
69 * @param scope the scope # where this local nametabe is openned
70 */
71 private LocalNametable(Nametable global, int scope)
72 {
73 _global = global;
74 _scope = scope;
75 }
76
77 /**
78 * Get the global
79 * @return the global
80 */
81 private Nametable getGlobal()
82 {
83 return _global;
84 }
85
86 /**
87 * {@inheritDoc}
88 */
89 public boolean containsName(String key)
90 {
91 return _locals.containsKey(key) || _global.containsName(key);
92 }
93
94 /**
95 * {@inheritDoc}
96 */
97 public void declare(String name, Object value)
98 {
99 _locals.put(name, value);
100 }
101
102 /**
103 * {@inheritDoc}
104 */
105 public Object assign(String name, Object value)
106 {
107 if (_locals.containsKey(name))
108 {
109 return _locals.put(name, value);
110 } else
111 {
112 //TODO: determine whether to allow local scope to reassign global
113 return _global.assign(name, value);
114 }
115 }
116
117 /**
118 * {@inheritDoc}
119 */
120 public Object access(String name)
121 {
122 if (_locals.containsKey(name))
123 {
124 return _locals.get(name);
125 } else
126 {
127 return _global.access(name);
128 }
129 }
130
131 /**
132 * {@inheritDoc}
133 */
134 public void undeclare(String name)
135 {
136 if (_locals.containsKey(name))
137 {
138 _locals.remove(name);
139 } else
140 {
141 //TODO: determine whether to allow local scope to undeclare global
142 _global.undeclare(name);
143 }
144 }
145
146 public String toString(){
147 StringBuffer sb = new StringBuffer();
148 sb.append("Scope=");
149 sb.append(_scope);
150 sb.append("\n");
151 sb.append("Locals=" + _locals + "\n");
152 sb.append("Global=" + _global + "\n");
153 return sb.toString();
154 }
155
156 public Map asMap(){
157 Map m = new HashMap(_global.asMap());
158 m.putAll(_locals);
159 return Collections.unmodifiableMap(m);
160 }
161 }
162
163 /**
164 * {@inheritDoc}
165 */
166 public NametableStack()
167 {
168 this(new HashMap());
169 }
170
171 /**
172 * {@inheritDoc}
173 * @param m the initial mapping
174 */
175 public NametableStack(Map m)
176 {
177 _nametable = new SimpleNametable(m);
178 }
179
180 /**
181 * Open a new scope for mappings. Return an integer that represents a scope id
182 * @return the new scope
183 */
184 public int newScope()
185 {
186 return _list.size();
187 }
188
189 public int newLocalScope()
190 {
191 _nametable = new LocalNametable(_nametable, _list.size());
192 return _list.size();
193 }
194
195 public void closeLocalScope(int i)
196 {
197 if (_nametable instanceof LocalNametable)
198 {
199 LocalNametable nt = (LocalNametable) _nametable;
200 if (nt._scope != i)
201 {
202 throw new IllegalArgumentException("Local scope " + i + " not matched");
203 } else
204 {
205 for (int k = _list.size(); k > i; k--)
206 {
207 _list.remove(k-1);
208 }
209 _nametable = nt.getGlobal();
210 }
211 } else
212 {
213 throw new IllegalStateException("Cannot find scope " + i);
214 }
215 }
216
217 /**
218 * Close a scope
219 * @param l the scope id
220 */
221 public void closeScope(int l)
222 {
223 if (_nametable instanceof LocalNametable)
224 {
225 if (l < ((LocalNametable) _nametable)._scope)
226 {
227 throw new IllegalStateException("Encounter unclosed local scope");
228 }
229 }
230 int n = _list.size();
231 if (l > n)
232 {
233 throw new IllegalArgumentException("The scope has been closed");
234 } else if (l < n)
235 {
236 int diff = n - l;
237 for (int i = 0; i < diff; i++)
238 {
239 _nametable.undeclare((String)_list.remove(n - i - 1));
240 }
241 }
242 }
243
244 /**
245 * Declare name value pair
246 * @param name
247 * @param value
248 * @return
249 */
250 public void declare(String name, Object value)
251 {
252 _nametable.declare(name, value);
253 _list.add(name);
254 }
255
256 /**
257 * Assign name/value pair
258 * @param name
259 * @param value
260 * @return
261 */
262 public Object assign(String name, Object value)
263 {
264 return _nametable.assign(name, value);
265 }
266
267 /**
268 * Resolve the value associated with key name
269 * @param name the key
270 * @return the value associated with key
271 */
272 public Object access(String name)
273 {
274 return _nametable.access(name);
275 }
276
277 /**
278 * Whether the map contains key name
279 * @param name the key
280 * @return true if map contains key name
281 */
282 public boolean containsName(String name)
283 {
284 return _nametable.containsName(name);
285 }
286
287 /**
288 * Return map representation of the nametable stack
289 * @return the map
290 */
291 public Map asMap()
292 {
293 return _nametable.asMap();
294 }
295
296 /**
297 * {@inheritDoc}
298 */
299 public String toString()
300 {
301 return _nametable.toString();
302 }
303 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 public class Scoreable implements Comparable
23 {
24
25 private int _score;
26
27 private Object _obj;
28
29 public Scoreable(int score, Object obj)
30 {
31 _score = score;
32 _obj = obj;
33 }
34
35 public Object getObject()
36 {
37 return _obj;
38 }
39
40 public int getScore()
41 {
42 return _score;
43 }
44
45 public int compareTo(Object o)
46 {
47 return getScore() - ((Scoreable) o).getScore();
48 }
49 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.Collections;
23 import java.util.Map;
24 /**
25 * A simple implementation of nametable
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 */
28 public class SimpleNametable implements Nametable
29 {
30
31 private final Map _table;
32
33 /**
34 * Constructor
35 * @param m the name
36 */
37 public SimpleNametable(Map m)
38 {
39 _table = m;
40 }
41
42 /**
43 * {@inheritDoc}
44 */
45 public void declare(String name, Object value)
46 {
47 if (_table.containsKey(name))
48 {
49 throw new IllegalArgumentException("Variable '" + name + "' has been declared.");
50 } else
51 {
52 _table.put(name, value);
53 }
54 }
55
56 /**
57 * {@inheritDoc}
58 */
59 public Object assign(String name, Object value)
60 {
61 if (_table.containsKey(name))
62 {
63 return _table.put(name, value);
64 } else
65 {
66 throw new IllegalArgumentException("Variable '" + name + "' has not been declared.");
67 }
68 }
69
70 /**
71 * {@inheritDoc}
72 */
73 public boolean containsName(String name)
74 {
75 return _table.containsKey(name);
76 }
77
78 /**
79 * {@inheritDoc}
80 */
81 public Object access(String name)
82 {
83 if (containsName(name))
84 {
85 return _table.get(name);
86 } else
87 {
88 throw new IllegalArgumentException("Varaible '" + name + "' has not been declared.");
89 }
90 }
91
92 /**
93 * {@inheritDoc}
94 */
95 public void undeclare(String name)
96 {
97 //TODO: need declaration check?
98 _table.remove(name);
99 }
100
101 public String toString()
102 {
103 return _table.toString();
104 }
105
106 /**
107 * Return the name table as a map
108 * @return unmodifiable map representation of the name table
109 */
110 public Map asMap()
111 {
112 return Collections.unmodifiableMap(_table);
113 }
114 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 /**
23 * An extension of java.util.Stack to have popUntil and pushReturnSize method
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: Stack.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
26 */
27 public class Stack extends java.util.Stack
28 {
29
30 /**
31 * {@inheritDoc}
32 */
33 public Stack()
34 {
35 }
36
37 /**
38 * Push the object ot the stack and return the size before pushing the object in
39 * @param o the object
40 * @return the size before the push
41 */
42 public int pushReturnSize(Object o)
43 {
44 int i = size();
45 push(o);
46 return i;
47 }
48
49 /**
50 * Pop until the stack reach size i
51 * @param i the size
52 */
53 public void popUntil(int i)
54 {
55 if (i < 0)
56 {
57 throw new IllegalArgumentException("Invalid size for popUtil");
58 } else if (i > size())
59 {
60 throw new RuntimeException("Stack already less than " + i);
61 }
62 while (size() > i)
63 {
64 pop();
65 }
66 }
67 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 /**
23 * A stack associated with current thread
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: ThreadLocalStack.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
26 */
27 public class ThreadLocalStack
28 {
29
30 /** the thread local * */
31 private ThreadLocal _local = new ThreadLocal();
32
33 /**
34 * Push a local object the the thread local stack
35 * @param localObject the local object
36 * @return the size after the push
37 */
38 public int pushLocal(Object localObject)
39 {
40 return getLocalStack().pushReturnSize(localObject);
41 }
42
43 /**
44 * get the local stack
45 * @return the stack
46 */
47 public Stack getLocalStack()
48 {
49 Stack s = (Stack) _local.get();
50 if (s == null)
51 {
52 s = new Stack();
53 _local.set(s);
54 }
55 return s;
56 }
57
58 /**
59 * Get the top-most local object in local stack
60 * @return the top-most local object in local stack
61 */
62 public Object getLocal()
63 {
64 return getLocalStack().peek();
65 }
66
67 /**
68 * Pop uptil certain size in local stack
69 * @param i the size
70 */
71 public void popLocalUtil(int i)
72 {
73 getLocalStack().popUntil(i);
74 }
75
76 /**
77 * Pop the top-most local object in threadlocal stack
78 * @return the top-most local object
79 */
80 public Object popLocal()
81 {
82 return getLocalStack().pop();
83 }
84 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.util.*;
23 /**
24 * A map that has it's map values changes tracked. It uses an inner map to keep the unchanged value and itself to track the changes
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: TrackedMap.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
27 */
28 public class TrackedMap extends HashMap
29 {
30
31 /** the track inner map * */
32 private Map _tracked;
33
34 /**
35 * {@inheritDoc}
36 */
37 public TrackedMap()
38 {
39 this(new HashMap());
40 }
41
42 /**
43 * {@inheritDoc}
44 */
45 public TrackedMap(int initialCapacity)
46 {
47 super(initialCapacity);
48 }
49
50 /**
51 * {@inheritDoc}
52 */
53 public TrackedMap(int initialCapacity, float loadFactor)
54 {
55 super(initialCapacity, loadFactor);
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 public TrackedMap(Map map)
62 {
63 super();
64 _tracked = map;
65 }
66
67 /**
68 * Return whether this map has been changes
69 * @return true if it has been changed
70 */
71 public boolean hasChanges()
72 {
73 return getChangedKeySet().size() > 0;
74 }
75
76 /**
77 * Return the key set of changed values
78 * @return the key set
79 */
80 public Set getChangedKeySet()
81 {
82 return super.keySet();
83 }
84
85 /**
86 * {@inheritDoc}
87 */
88 public Object get(Object key)
89 {
90 if (containsKey(key))
91 {
92 return super.get(key);
93 } else
94 {
95 return _tracked.get(key);
96 }
97 }
98
99 /**
100 * Make this map as up-to-date.
101 */
102 public void makeUpToDate()
103 {
104 Iterator it = super.keySet().iterator();
105 while (it.hasNext())
106 {
107 Object key = it.next();
108 Object o = super.get(key);
109 _tracked.put(key, o);
110 }
111 super.clear();
112 }
113
114 /**
115 * Clear all the changes
116 */
117 public void clearChanges()
118 {
119 super.clear();
120 }
121
122 /**
123 * {@inheritDoc}
124 */
125 public void clear()
126 {
127 super.clear();
128 _tracked.clear();
129 }
130
131 /**
132 * {@inheritDoc}
133 */
134 public boolean containsKey(Object key)
135 {
136 return super.containsKey(key) || _tracked.containsKey(key);
137 }
138
139 /**
140 * {@inheritDoc}
141 */
142 public boolean containsValue(Object value)
143 {
144 return super.containsValue(value) || _tracked.containsValue(value);
145 }
146
147 /**
148 * {@inheritDoc}
149 */
150 public Set entrySet()
151 {
152 Set s = new HashSet(_tracked.entrySet());
153 s.addAll(super.entrySet());
154 return s;
155 }
156
157 /**
158 * {@inheritDoc}
159 */
160 public boolean isEmpty()
161 {
162 return super.isEmpty() && _tracked.isEmpty();
163 }
164
165 /**
166 * {@inheritDoc}
167 */
168 public Set keySet()
169 {
170 Set s = new HashSet(_tracked.keySet());
171 s.addAll(super.keySet());
172 return s;
173 }
174
175 /**
176 * {@inheritDoc}
177 */
178 public Object remove(Object key)
179 {
180 Object o = get(key);
181 put(key, null);
182 return o;
183 }
184
185 /**
186 * {@inheritDoc}
187 */
188 public int size()
189 {
190 return keySet().size();
191 }
192
193 /**
194 * {@inheritDoc}
195 */
196 public Collection values()
197 {
198 HashSet set = new HashSet(_tracked.values());
199 set.addAll(super.values());
200 return set;
201 }
202 }
0
1 package org.onemind.commons.java.datastructure;
2
3 import java.io.*;
4 import java.sql.Types;
5 import java.util.HashMap;
6 import java.util.Map;
7 import javax.xml.parsers.*;
8 import org.onemind.commons.java.lang.reflect.ReflectUtils;
9 import org.onemind.commons.java.xml.digest.*;
10 import org.xml.sax.Attributes;
11 import org.xml.sax.SAXException;
12 /**
13 * An XmlPropertiesReader read a properties out of an xml file. The xml is read
14 * using dom parser. It support all the java primitive types
15 * and in addition creation of instance of ElementDigester
16 * @author TiongHiang Lee (thlee@onemindsoft.org)
17 * @version $Id: XmlProperties.java,v 1.3 2005/06/22 22:57:52 thlee Exp $ $Name: $
18 */
19 public class XmlProperties extends HashMap
20 {
21 /**
22 * Constructor
23 * @param filename the file name
24 * @throws FileNotFoundException
25 * @throws IOException
26 * @throws SAXException
27 * @throws ParserConfigurationException
28 */
29 public XmlProperties(String filename) throws FileNotFoundException, ParserConfigurationException, SAXException, IOException
30 {
31 this(new FileInputStream(filename));
32 }
33
34 /**
35 * Constructor
36 * @param stream
37 * @throws ParserConfigurationException
38 * @throws SAXException
39 * @throws IOException
40 */
41 public XmlProperties(InputStream is) throws ParserConfigurationException, SAXException, IOException
42 {
43 SAXParserFactory factory = SAXParserFactory.newInstance();
44 // Parse the input
45 SAXParser saxParser = factory.newSAXParser();
46 SaxDigesterHandler handler = new SaxDigesterHandler();
47 handler.addDigester("Properties", new XmlPropertyElementDigester("Property", this));
48 saxParser.parse(is, handler);
49 }
50 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.datastructure;
21
22 import java.sql.Types;
23 import java.util.HashMap;
24 import java.util.Map;
25 import org.onemind.commons.java.lang.reflect.ReflectUtils;
26 import org.onemind.commons.java.xml.digest.*;
27 import org.xml.sax.Attributes;
28 import org.xml.sax.SAXException;
29 /**
30 * A Sax elemenbt handler that can handle parsing properties specified in an xml file
31 * This syntax of the xml is something like
32 * <Property name="defaultvalue" value="default"/>
33 <Property name="shortvalue" type="short" value="1"/>
34 <Property name="intvalue" type="int" value="1"/>
35 <Property name="longvalue" type="long" value="1"/>
36 <Property name="floatvalue" type="float" value="1"/>
37 <Property name="doublevalue" type="double" value="1"/>
38 <Property name="charvalue" type="char" value="c"/>
39 <Property name="stringvalue" type="string" value="string"/>
40 * @author TiongHiang Lee (thlee@onemindsoft.org)
41 */
42 public class XmlPropertyElementDigester extends DefaultDigester implements ElementDigester
43 {
44
45 private static final Map _typeMap;
46 static
47 {
48 _typeMap = new HashMap();
49 _typeMap.put("short", new Integer(Types.SMALLINT));
50 _typeMap.put("int", new Integer(Types.INTEGER));
51 _typeMap.put("long", new Integer(Types.BIGINT));
52 _typeMap.put("float", new Integer(Types.FLOAT));
53 _typeMap.put("double", new Integer(Types.DOUBLE));
54 _typeMap.put("boolean", new Integer(Types.BOOLEAN));
55 _typeMap.put("char", new Integer(Types.CHAR));
56 _typeMap.put("string", new Integer(Types.VARCHAR));
57 }
58
59 private final Map _prop;
60
61 public XmlPropertyElementDigester(String elementName, Map prop)
62 {
63 super(elementName);
64 _prop = prop;
65 }
66
67 /**
68 * {@inheritDoc}
69 */
70 public void startDigest(SaxDigesterHandler handler, Attributes attrs) throws SAXException
71 {
72 String name = attrs.getValue("name");
73 String type = attrs.getValue("type");
74 String value = attrs.getValue("value");
75 String clazz = attrs.getValue("class");
76 if (name == null)
77 {
78 throw new SAXException("name attribute must exists on property");
79 }
80 if (type != null && clazz != null)
81 {
82 throw new SAXException("Both type and class cannot be specified on same property");
83 }
84 if (clazz != null)
85 {
86 try
87 {
88 Class c = ReflectUtils.getClass(clazz);
89 Object obj = (Object) ReflectUtils.newInstance(c, null);
90 String digest = attrs.getValue("digest");
91 if (digest != null && digest.equalsIgnoreCase("true"))
92 {
93 if (clazz != null)
94 {
95 if (!ElementDigester.class.isAssignableFrom(obj.getClass()))
96 {
97 throw new SAXException("Class " + clazz + " is not a subclass of ElementDigester");
98 }
99 ElementDigester dig = (ElementDigester) obj;
100 handler.addSubDigester(dig);
101 _prop.put(name, dig);
102 }
103 } else
104 {//just put the object as a property
105 _prop.put(name, obj);
106 }
107 } catch (Exception e)
108 {
109 throw new SAXException(e.getMessage(), e);
110 }
111 } else if (type != null)
112 {
113 Object v = null;
114 Integer typeInt = (Integer) _typeMap.get(type);
115 if (typeInt == null)
116 {
117 throw new SAXException("Unrecognized property type " + type);
118 } else
119 {
120 switch (typeInt.intValue())
121 {
122 case Types.SMALLINT :
123 v = Short.valueOf(value);
124 break;
125 case Types.INTEGER :
126 v = Integer.valueOf(value);
127 break;
128 case Types.BIGINT :
129 v = Long.valueOf(value);
130 break;
131 case Types.FLOAT :
132 v = Float.valueOf(value);
133 break;
134 case Types.DOUBLE :
135 v = Double.valueOf(value);
136 break;
137 case Types.BOOLEAN :
138 v = Boolean.valueOf(value);
139 break;
140 case Types.CHAR :
141 v = new Character(value.charAt(0));
142 break;
143 case Types.VARCHAR :
144 v = value;
145 break;
146 default :
147 throw new IllegalStateException("Unrecognized property type " + type);
148 }
149 }
150 _prop.put(name, v);
151 } else
152 {
153 _prop.put(name, value);
154 }
155 }
156
157 /**
158 * {@inheritDoc}
159 */
160 public void endDigest(SaxDigesterHandler handler) throws SAXException
161 {
162 // TODO Auto-generated method stub
163 }
164
165 /**
166 * {@inheritDoc}
167 */
168 public void characters(SaxDigesterHandler handler, char[] chars, int offset, int length) throws SAXException
169 {
170 // TODO Auto-generated method stub
171 }
172 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8 * This library is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
11 * Lesser General Public License for more details.
12 *
13 * You should have received a copy of the GNU Lesser General Public
14 * License along with this library; if not, write to the Free Software
15 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
16 *
17 * Email: thlee@onemindsoft.org
18 */
19
20 package org.onemind.commons.java.event;
21
22 import java.util.EventObject;
23 /**
24 * Interface for firing event
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: EventFirer.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
27 */
28 public interface EventFirer
29 {
30
31 /**
32 * Fire an event
33 * @param listener the listener
34 * @param evt the event
35 */
36 public void fireEvent(EventListener listener, EventObject evt);
37 }
0 /*
1 * Copyright (C) 2004 TiongHiang Lee
2 *
3 * This library is free software; you can redistribute it and/or
4 * modify it under the terms of the GNU Lesser General Public
5 * License as published by the Free Software Foundation; either
6 * version 2.1 of the License, or (at your option) any later version.
7 *
8