Codebase list libonemind-commons-java-java / upstream/1.5.5
Imported Upstream version 1.5.5 gregor herrmann 12 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 * 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 public interface EventHandler
25 {
26 public void handleEvent(EventObject evt);
27 }
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 /**
23 * An tagging event listener interface
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: EventListener.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
26 */
27 public interface EventListener
28 {
29 }
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.ArrayList;
23 import java.util.Collection;
24 import java.util.Collections;
25 import java.util.EventObject;
26 import java.util.Iterator;
27 import java.util.List;
28 /**
29 * A listener list contains listeners and fire events
30 * @author TiongHiang Lee (thlee@onemindsoft.org)
31 * @version $Id: EventListenerList.java,v 1.2 2004/08/26 12:33:16 thlee Exp $ $Name: $
32 */
33 public class EventListenerList
34 {
35
36 /** the listeners * */
37 private List _eventListeners = new ArrayList();
38
39 /**
40 * {@inheritDoc}
41 */
42 public EventListenerList()
43 {
44 }
45
46 /**
47 * Get the listeners
48 * @return the listeners
49 */
50 public Collection getListeners()
51 {
52 return Collections.unmodifiableCollection(_eventListeners);
53 }
54
55 /**
56 * Fire an event to all listeneres
57 * @param firer the firer
58 * @param obj the event object
59 */
60 public void fireEvent(EventFirer firer, EventObject obj)
61 {
62 Iterator it = _eventListeners.iterator();
63 while (it.hasNext())
64 {
65 EventListener listener = (EventListener) it.next();
66 firer.fireEvent(listener, obj);
67 }
68 }
69
70 /**
71 * Add a listener
72 * @param listener the listener
73 */
74 public void addListener(EventListener listener)
75 {
76 _eventListeners.add(listener);
77 }
78
79 /**
80 * Remove a listener
81 * @param listener the listener
82 */
83 public void removeListener(EventListener listener)
84 {
85 _eventListeners.remove(listener);
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.html.css;
21
22 import java.util.*;
23 import org.onemind.commons.java.lang.Enum;
24 /**
25 * Contains css related method and constants
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: Css.java,v 1.3 2005/03/07 17:28:17 thlee Exp $ $Name: $
28 */
29 public class Css
30 {
31
32 /**
33 * Represent the attribute (Currently contains only visual attr)
34 * @author TiongHiang Lee (thlee@onemindsoft.org)
35 * @version $Id: Css.java,v 1.3 2005/03/07 17:28:17 thlee Exp $ $Name: $
36 */
37 public static final class Attr extends Enum
38 {
39
40 private static Map _cssAttrs = new HashMap();
41
42 public static final Attr background = new Attr("background");
43
44 public static final Attr background_attachment = new Attr("background-attachment");
45
46 public static final Attr background_color = new Attr("background-color");
47
48 public static final Attr background_image = new Attr("background-image");
49
50 public static final Attr background_position = new Attr("background-position");
51
52 public static final Attr background_repeat = new Attr("background-repeat");
53
54 public static final Attr border = new Attr("border");
55
56 public static final Attr border_bottom = new Attr("border-bottom");
57
58 public static final Attr border_bottom_color = new Attr("border-bottom-color");
59
60 public static final Attr border_bottom_style = new Attr("border-bottom-style");
61
62 public static final Attr border_bottom_width = new Attr("border-bottom-width");
63
64 public static final Attr border_collapse = new Attr("border-collapse");
65
66 public static final Attr border_color = new Attr("border-color");
67
68 public static final Attr border_left = new Attr("border-left");
69
70 public static final Attr border_left_color = new Attr("border-left-color");
71
72 public static final Attr border_left_style = new Attr("border-left-style");
73
74 public static final Attr border_left_width = new Attr("border-left-width");
75
76 public static final Attr border_right = new Attr("border-right");
77
78 public static final Attr border_right_color = new Attr("border-right-color");
79
80 public static final Attr border_right_style = new Attr("border-right-style");
81
82 public static final Attr border_right_width = new Attr("border-right-width");
83
84 public static final Attr border_spacing = new Attr("border-spacing");
85
86 public static final Attr border_style = new Attr("border-style");
87
88 public static final Attr border_top = new Attr("border-top");
89
90 public static final Attr border_top_color = new Attr("border-top-color");
91
92 public static final Attr border_top_style = new Attr("border-top-style");
93
94 public static final Attr border_top_width = new Attr("border-top-width");
95
96 public static final Attr border_width = new Attr("border-width");
97
98 public static final Attr bottom = new Attr("bottom");
99
100 public static final Attr caption_side = new Attr("caption-side");
101
102 public static final Attr clear = new Attr("clear");
103
104 public static final Attr clip = new Attr("clip");
105
106 public static final Attr color = new Attr("color");
107
108 public static final Attr content = new Attr("content");
109
110 public static final Attr counter_increment = new Attr("counter-increment");
111
112 public static final Attr counter_reset = new Attr("counter-reset");
113
114 public static final Attr cursor = new Attr("cursor");
115
116 public static final Attr direction = new Attr("direction");
117
118 public static final Attr display = new Attr("display");
119
120 public static final Attr empty_cells = new Attr("empty-cells");
121
122 public static final Attr float_ = new Attr("float");
123
124 public static final Attr font = new Attr("font");
125
126 public static final Attr font_family = new Attr("font-family");
127
128 public static final Attr font_size = new Attr("font-size");
129
130 public static final Attr font_size_adjust = new Attr("font-size-adjust");
131
132 public static final Attr font_stretch = new Attr("font-stretch");
133
134 public static final Attr font_style = new Attr("font-style");
135
136 public static final Attr font_variant = new Attr("font-variant");
137
138 public static final Attr font_weight = new Attr("font-weight");
139
140 public static final Attr height = new Attr("height");
141
142 public static final Attr left = new Attr("left");
143
144 public static final Attr letter_spacing = new Attr("letter-spacing");
145
146 public static final Attr line_height = new Attr("line-height");
147
148 public static final Attr list_style = new Attr("list-style");
149
150 public static final Attr list_style_image = new Attr("list-style-image");
151
152 public static final Attr list_style_position = new Attr("list-style-position");
153
154 public static final Attr list_style_type = new Attr("list-style-type");
155
156 public static final Attr margin = new Attr("margin");
157
158 public static final Attr margin_bottom = new Attr("margin-bottom");
159
160 public static final Attr margin_left = new Attr("margin-left");
161
162 public static final Attr margin_right = new Attr("margin-right");
163
164 public static final Attr margin_top = new Attr("margin-top");
165
166 public static final Attr marker_offset = new Attr("marker-offset");
167
168 public static final Attr max_height = new Attr("max-height");
169
170 public static final Attr max_width = new Attr("max-width");
171
172 public static final Attr min_height = new Attr("min-height");
173
174 public static final Attr min_width = new Attr("min-width");
175
176 public static final Attr outline = new Attr("outline");
177
178 public static final Attr outline_color = new Attr("outline-color");
179
180 public static final Attr outline_style = new Attr("outline-style");
181
182 public static final Attr outline_width = new Attr("outline-width");
183
184 public static final Attr overflow = new Attr("overflow");
185
186 public static final Attr padding = new Attr("padding");
187
188 public static final Attr padding_bottom = new Attr("padding-bottom");
189
190 public static final Attr padding_left = new Attr("padding-left");
191
192 public static final Attr padding_right = new Attr("padding-right");
193
194 public static final Attr padding_top = new Attr("padding-top");
195
196 public static final Attr position = new Attr("position");
197
198 public static final Attr quotes = new Attr("quotes");
199
200 public static final Attr right = new Attr("right");
201
202 public static final Attr table_layout = new Attr("table-layout");
203
204 public static final Attr text_align = new Attr("text-align");
205
206 public static final Attr text_decoration = new Attr("text-decoration");
207
208 public static final Attr text_indent = new Attr("text-indent");
209
210 public static final Attr text_shadow = new Attr("text-shadow");
211
212 public static final Attr text_transform = new Attr("text-transform");
213
214 public static final Attr top = new Attr("top");
215
216 public static final Attr unicode_bidi = new Attr("unicode-bidi");
217
218 public static final Attr vertical_align = new Attr("vertical-align");
219
220 public static final Attr visibility = new Attr("visibility");
221
222 public static final Attr white_space = new Attr("white-space");
223
224 public static final Attr width = new Attr("width");
225
226 public static final Attr word_spacing = new Attr("word-spacing");
227
228 public static final Attr z_index = new Attr("z-index");
229 static
230 {
231 _cssAttrs.put(background.toString(), background);
232 _cssAttrs.put(background_attachment.toString(), background_attachment);
233 _cssAttrs.put(background_color.toString(), background_color);
234 _cssAttrs.put(background_image.toString(), background_image);
235 _cssAttrs.put(background_position.toString(), background_position);
236 _cssAttrs.put(background_repeat.toString(), background_repeat);
237 _cssAttrs.put(border.toString(), border);
238 _cssAttrs.put(border_bottom.toString(), border_bottom);
239 _cssAttrs.put(border_bottom_color.toString(), border_bottom_color);
240 _cssAttrs.put(border_bottom_style.toString(), border_bottom_style);
241 _cssAttrs.put(border_bottom_width.toString(), border_bottom_width);
242 _cssAttrs.put(border_collapse.toString(), border_collapse);
243 _cssAttrs.put(border_color.toString(), border_color);
244 _cssAttrs.put(border_left.toString(), border_left);
245 _cssAttrs.put(border_left_color.toString(), border_left_color);
246 _cssAttrs.put(border_left_style.toString(), border_left_style);
247 _cssAttrs.put(border_left_width.toString(), border_left_width);
248 _cssAttrs.put(border_right.toString(), border_right);
249 _cssAttrs.put(border_right_color.toString(), border_right_color);
250 _cssAttrs.put(border_right_style.toString(), border_right_style);
251 _cssAttrs.put(border_right_width.toString(), border_right_width);
252 _cssAttrs.put(border_spacing.toString(), border_spacing);
253 _cssAttrs.put(border_style.toString(), border_style);
254 _cssAttrs.put(border_top.toString(), border_top);
255 _cssAttrs.put(border_top_color.toString(), border_top_color);
256 _cssAttrs.put(border_top_style.toString(), border_top_style);
257 _cssAttrs.put(border_top_width.toString(), border_top_width);
258 _cssAttrs.put(border_width.toString(), border_width);
259 _cssAttrs.put(bottom.toString(), bottom);
260 _cssAttrs.put(caption_side.toString(), caption_side);
261 _cssAttrs.put(clear.toString(), clear);
262 _cssAttrs.put(clip.toString(), clip);
263 _cssAttrs.put(color.toString(), color);
264 _cssAttrs.put(content.toString(), content);
265 _cssAttrs.put(counter_increment.toString(), counter_increment);
266 _cssAttrs.put(counter_reset.toString(), counter_reset);
267 _cssAttrs.put(cursor.toString(), cursor);
268 _cssAttrs.put(direction.toString(), direction);
269 _cssAttrs.put(display.toString(), display);
270 _cssAttrs.put(empty_cells.toString(), empty_cells);
271 _cssAttrs.put(float_.toString(), float_);
272 _cssAttrs.put(font.toString(), font);
273 _cssAttrs.put(font_family.toString(), font_family);
274 _cssAttrs.put(font_size.toString(), font_size);
275 _cssAttrs.put(font_size_adjust.toString(), font_size_adjust);
276 _cssAttrs.put(font_stretch.toString(), font_stretch);
277 _cssAttrs.put(font_style.toString(), font_style);
278 _cssAttrs.put(font_variant.toString(), font_variant);
279 _cssAttrs.put(font_weight.toString(), font_weight);
280 _cssAttrs.put(height.toString(), height);
281 _cssAttrs.put(left.toString(), left);
282 _cssAttrs.put(letter_spacing.toString(), letter_spacing);
283 _cssAttrs.put(line_height.toString(), line_height);
284 _cssAttrs.put(list_style.toString(), list_style);
285 _cssAttrs.put(list_style_image.toString(), list_style_image);
286 _cssAttrs.put(list_style_position.toString(), list_style_position);
287 _cssAttrs.put(list_style_type.toString(), list_style_type);
288 _cssAttrs.put(margin.toString(), margin);
289 _cssAttrs.put(margin_bottom.toString(), margin_bottom);
290 _cssAttrs.put(margin_left.toString(), margin_left);
291 _cssAttrs.put(margin_right.toString(), margin_right);
292 _cssAttrs.put(margin_top.toString(), margin_top);
293 _cssAttrs.put(marker_offset.toString(), marker_offset);
294 _cssAttrs.put(max_height.toString(), max_height);
295 _cssAttrs.put(max_width.toString(), max_width);
296 _cssAttrs.put(min_height.toString(), min_height);
297 _cssAttrs.put(min_width.toString(), min_width);
298 _cssAttrs.put(outline.toString(), outline);
299 _cssAttrs.put(outline_color.toString(), outline_color);
300 _cssAttrs.put(outline_style.toString(), outline_style);
301 _cssAttrs.put(outline_width.toString(), outline_width);
302 _cssAttrs.put(overflow.toString(), overflow);
303 _cssAttrs.put(padding.toString(), padding);
304 _cssAttrs.put(padding_bottom.toString(), padding_bottom);
305 _cssAttrs.put(padding_left.toString(), padding_left);
306 _cssAttrs.put(padding_right.toString(), padding_right);
307 _cssAttrs.put(padding_top.toString(), padding_top);
308 _cssAttrs.put(position.toString(), position);
309 _cssAttrs.put(quotes.toString(), quotes);
310 _cssAttrs.put(right.toString(), right);
311 _cssAttrs.put(table_layout.toString(), table_layout);
312 _cssAttrs.put(text_align.toString(), text_align);
313 _cssAttrs.put(text_decoration.toString(), text_decoration);
314 _cssAttrs.put(text_indent.toString(), text_indent);
315 _cssAttrs.put(text_shadow.toString(), text_shadow);
316 _cssAttrs.put(text_transform.toString(), text_transform);
317 _cssAttrs.put(top.toString(), top);
318 _cssAttrs.put(unicode_bidi.toString(), unicode_bidi);
319 _cssAttrs.put(vertical_align.toString(), vertical_align);
320 _cssAttrs.put(visibility.toString(), visibility);
321 _cssAttrs.put(white_space.toString(), white_space);
322 _cssAttrs.put(width.toString(), width);
323 _cssAttrs.put(word_spacing.toString(), word_spacing);
324 _cssAttrs.put(z_index.toString(), z_index);
325 }
326
327 /**
328 * Resolve the str to an attr representation
329 * @param str the str
330 * @return the Attribute
331 */
332 public static Attr resolveAttr(String str)
333 {
334 return (Attr) _cssAttrs.get(str);
335 }
336
337 /**
338 * Return all the defined css attributes
339 * @return all the defined css attribute objects
340 */
341 public static List getAllAttrs()
342 {
343 return new ArrayList(_cssAttrs.values());
344 }
345
346 /**
347 * Constructor
348 * @param name the name of the attribute
349 */
350 private Attr(String name)
351 {
352 super(name);
353 }
354 }
355
356 /**
357 * The css field definitions
358 * @author TiongHiang Lee (thlee@onemindsoft.org)
359 * @version $Id: Css.java,v 1.3 2005/03/07 17:28:17 thlee Exp $ $Name: $
360 */
361 public static final class AttrUnit extends Enum
362 {
363
364 public static final AttrUnit deg = new AttrUnit("deg");
365
366 public static final AttrUnit grad = new AttrUnit("grad");
367
368 public static final AttrUnit hz = new AttrUnit("Hz");
369
370 public static final AttrUnit khz = new AttrUnit("kHz");
371
372 public static final AttrUnit ms = new AttrUnit("ms");
373
374 public static final AttrUnit percent = new AttrUnit("%");
375
376 public static final AttrUnit point = new AttrUnit("pt");
377
378 public static final AttrUnit rad = new AttrUnit("rad");
379
380 public static final AttrUnit s = new AttrUnit("s");
381
382 /**
383 * {@inheritDoc}
384 */
385 private AttrUnit(String name)
386 {
387 super(name);
388 }
389 }
390
391 /**
392 * The offset value
393 * @author TiongHiang Lee (thlee@onemindsoft.org)
394 * @version $Id: Css.java,v 1.3 2005/03/07 17:28:17 thlee Exp $ $Name: $
395 */
396 public static class AttrValue extends Enum
397 {
398
399 public static final AttrValue absolute = new AttrValue("absolute");
400
401 public static final AttrValue armenian = new AttrValue("armenian");
402
403 public static final AttrValue auto = new AttrValue("auto");
404
405 public static final AttrValue baseline = new AttrValue("baseline");
406
407 public static final AttrValue bidi_override = new AttrValue("bidi-override");
408
409 public static final AttrValue block = new AttrValue("block");
410
411 public static final AttrValue bold = new AttrValue("bold");
412
413 public static final AttrValue bolder = new AttrValue("bolder");
414
415 public static final AttrValue both = new AttrValue("both");
416
417 public static final AttrValue bottom = new AttrValue("bottom");
418
419 public static final AttrValue capitalize = new AttrValue("capitalize");
420
421 public static final AttrValue caption = new AttrValue("caption");
422
423 public static final AttrValue center = new AttrValue("center");
424
425 public static final AttrValue circle = new AttrValue("circle");
426
427 public static final AttrValue cjk_ideographic = new AttrValue("cjk-ideographic");
428
429 public static final AttrValue close_quote = new AttrValue("close-quote");
430
431 public static final AttrValue collapse = new AttrValue("collapse");
432
433 public static final AttrValue compact = new AttrValue("compact");
434
435 public static final AttrValue condensed = new AttrValue("condensed");
436
437 public static final AttrValue crosshair = new AttrValue("crosshair");
438
439 public static final AttrValue decimal = new AttrValue("decimal");
440
441 public static final AttrValue decimal_leading_zero = new AttrValue("decimal-leading-zero");
442
443 public static final AttrValue default_ = new AttrValue("default");
444
445 public static final AttrValue disc = new AttrValue("disc");
446
447 public static final AttrValue e_resize = new AttrValue("e-resize");
448
449 public static final AttrValue embed = new AttrValue("embed");
450
451 public static final AttrValue expanded = new AttrValue("expanded");
452
453 public static final AttrValue extra_condensed = new AttrValue("extra-condensed");
454
455 public static final AttrValue extra_expanded = new AttrValue("extra-expanded");
456
457 public static final AttrValue fixed = new AttrValue("fixed");
458
459 public static final AttrValue georgian = new AttrValue("georgian");
460
461 public static final AttrValue hebrew = new AttrValue("hebrew");
462
463 public static final AttrValue help = new AttrValue("help");
464
465 public static final AttrValue hidden = new AttrValue("hidden");
466
467 public static final AttrValue hide = new AttrValue("hide");
468
469 public static final AttrValue hiragana = new AttrValue("hiragana");
470
471 public static final AttrValue hiragana_iroha = new AttrValue("hiragana-iroha");
472
473 public static final AttrValue icon = new AttrValue("icon");
474
475 public static final AttrValue inherit = new AttrValue("inherit");
476
477 public static final AttrValue inline = new AttrValue("inline");
478
479 public static final AttrValue inline_table = new AttrValue("inline-table");
480
481 public static final AttrValue inside = new AttrValue("inside");
482
483 public static final AttrValue invert = new AttrValue("invert");
484
485 public static final AttrValue italic = new AttrValue("italic");
486
487 public static final AttrValue justify = new AttrValue("justify");
488
489 public static final AttrValue katakana = new AttrValue("katakana");
490
491 public static final AttrValue katakana_iroha = new AttrValue("katakana-iroha");
492
493 public static final AttrValue left = new AttrValue("left");
494
495 public static final AttrValue lighter = new AttrValue("lighter");
496
497 public static final AttrValue list_item = new AttrValue("list-item");
498
499 public static final AttrValue lower_alpha = new AttrValue("lower-alpha");
500
501 public static final AttrValue lower_greek = new AttrValue("lower-greek");
502
503 public static final AttrValue lower_latin = new AttrValue("lower-latin");
504
505 public static final AttrValue lower_roman = new AttrValue("lower-roman");
506
507 public static final AttrValue lowercase = new AttrValue("lowercase");
508
509 public static final AttrValue ltr = new AttrValue("ltr");
510
511 public static final AttrValue marker = new AttrValue("marker");
512
513 public static final AttrValue menu = new AttrValue("menu");
514
515 public static final AttrValue message_box = new AttrValue("message-box");
516
517 public static final AttrValue middle = new AttrValue("middle");
518
519 public static final AttrValue move = new AttrValue("move");
520
521 public static final AttrValue n_resize = new AttrValue("n-resize");
522
523 public static final AttrValue narrower = new AttrValue("narrower");
524
525 public static final AttrValue ne_resize = new AttrValue("ne-resize");
526
527 public static final AttrValue no_open_quote = new AttrValue("no-open-quote");
528
529 public static final AttrValue no_repeat = new AttrValue("no-repeat");
530
531 public static final AttrValue none = new AttrValue("none");
532
533 public static final AttrValue normal = new AttrValue("normal");
534
535 public static final AttrValue nowrap = new AttrValue("nowrap");
536
537 public static final AttrValue nw_resize = new AttrValue("nw-resize");
538
539 public static final AttrValue oblique = new AttrValue("oblique");
540
541 public static final AttrValue open_quote = new AttrValue("open-quote");
542
543 public static final AttrValue outside = new AttrValue("outside");
544
545 public static final AttrValue pointer = new AttrValue("pointer");
546
547 public static final AttrValue pre = new AttrValue("pre");
548
549 public static final AttrValue relative = new AttrValue("relative");
550
551 public static final AttrValue repeat = new AttrValue("repeat");
552
553 public static final AttrValue repeat_x = new AttrValue("repeat-x");
554
555 public static final AttrValue repeat_y = new AttrValue("repeat-y");
556
557 public static final AttrValue right = new AttrValue("right");
558
559 public static final AttrValue rtl = new AttrValue("rtl");
560
561 public static final AttrValue run_in = new AttrValue("rul-in");
562
563 public static final AttrValue s_resize = new AttrValue("s-resize");
564
565 public static final AttrValue scroll = new AttrValue("scroll");
566
567 public static final AttrValue se_resize = new AttrValue("se-resize");
568
569 public static final AttrValue semi_condensed = new AttrValue("semi-condensed");
570
571 public static final AttrValue semi_expanded = new AttrValue("semi-expanded");
572
573 public static final AttrValue separate = new AttrValue("separate");
574
575 public static final AttrValue show = new AttrValue("show");
576
577 public static final AttrValue small_caps = new AttrValue("small-caps");
578
579 public static final AttrValue small_caption = new AttrValue("small-caption");
580
581 public static final AttrValue square = new AttrValue("square");
582
583 public static final AttrValue static_ = new AttrValue("static");
584
585 public static final AttrValue status_bar = new AttrValue("status-bar");
586
587 public static final AttrValue sub = new AttrValue("sub");
588
589 public static final AttrValue super_ = new AttrValue("super");
590
591 public static final AttrValue sw_resize = new AttrValue("sw-resize");
592
593 public static final AttrValue table = new AttrValue("table");
594
595 public static final AttrValue table_caption = new AttrValue("table-caption");
596
597 public static final AttrValue table_cell = new AttrValue("table-cell");
598
599 public static final AttrValue table_column = new AttrValue("table-column");
600
601 public static final AttrValue table_column_group = new AttrValue("table-column-group");
602
603 public static final AttrValue table_footer_group = new AttrValue("table-footer-group");
604
605 public static final AttrValue table_header_group = new AttrValue("table-header-group");
606
607 public static final AttrValue table_row = new AttrValue("table-row");
608
609 public static final AttrValue table_row_group = new AttrValue("table-row-group");
610
611 public static final AttrValue text = new AttrValue("text");
612
613 public static final AttrValue text_bottom = new AttrValue("text-bottom");
614
615 public static final AttrValue text_top = new AttrValue("text-top");
616
617 public static final AttrValue top = new AttrValue("top");
618
619 public static final AttrValue transparent = new AttrValue("transparent");
620
621 public static final AttrValue ultra_condensed = new AttrValue("ultra-condensed");
622
623 public static final AttrValue ultra_expanded = new AttrValue("ultra-expanded");
624
625 public static final AttrValue upper_alpha = new AttrValue("upper-alpha");
626
627 public static final AttrValue upper_latin = new AttrValue("upper-latin");
628
629 public static final AttrValue upper_roman = new AttrValue("upper-roman");
630
631 public static final AttrValue uppercase = new AttrValue("uppercase");
632
633 public static final AttrValue visible = new AttrValue("visible");
634
635 public static final AttrValue w_resize = new AttrValue("w-resize");
636
637 public static final AttrValue wait = new AttrValue("wait");
638
639 public static final AttrValue wider = new AttrValue("wider");
640
641 /**
642 * {@inheritDoc}
643 */
644 private AttrValue(String name)
645 {
646 super(name);
647 }
648 }
649 }
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.lang;
21
22 /**
23 * Represent a config exception
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: ConfigurationException.java,v 1.2 2004/08/26 12:33:17 thlee Exp $ $Name: $
26 */
27 public class ConfigurationException extends RuntimeException
28 {
29
30 /**
31 * {@inheritDoc}
32 */
33 public ConfigurationException()
34 {
35 super();
36 }
37
38 /**
39 * {@inheritDoc}
40 */
41 public ConfigurationException(String arg0)
42 {
43 super(arg0);
44 }
45
46 /**
47 * {@inheritDoc}
48 */
49 public ConfigurationException(String arg0, Throwable arg1)
50 {
51 super(arg0, arg1);
52 }
53
54 /**
55 * {@inheritDoc}
56 */
57 public ConfigurationException(Throwable arg0)
58 {
59 super(arg0);
60 }
61 }
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.lang;
21
22 /**
23 * Represents an enum
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: Enum.java,v 1.2 2004/08/26 12:33:17 thlee Exp $ $Name: $
26 */
27 public abstract class Enum
28 {
29
30 /** the name * */
31 private String _name;
32
33 /**
34 * Constructor
35 * @param name the name
36 */
37 public Enum(String name)
38 {
39 _name = name;
40 }
41
42 /**
43 * Return the name {@inheritDoc}
44 */
45 public String toString()
46 {
47 return _name;
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.lang;
21
22 /**
23 * A mutable double
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: MutableDouble.java,v 1.3 2004/09/03 13:24:14 thlee Exp $ $Name: $
26 */
27 public class MutableDouble extends Number
28 {
29
30 /** the value * */
31 private double _value;
32
33 /**
34 * {@inheritDoc}
35 * @param l the value
36 */
37 public MutableDouble(double l)
38 {
39 _value = l;
40 }
41
42 /**
43 * Set the double value
44 * @param l the value
45 */
46 public final void set(double l)
47 {
48 _value = l;
49 }
50
51 /**
52 * {@inheritDoc}
53 */
54 public final byte byteValue()
55 {
56 return (byte) _value;
57 }
58
59 /**
60 * {@inheritDoc}
61 */
62 public final double doubleValue()
63 {
64 return _value;
65 }
66
67 /**
68 * {@inheritDoc}
69 */
70 public final float floatValue()
71 {
72 return (float) _value;
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 public final int intValue()
79 {
80 return (int) _value;
81 }
82
83 /**
84 * {@inheritDoc}
85 */
86 public final long longValue()
87 {
88 return (long) _value;
89 }
90
91 /**
92 * {@inheritDoc}
93 */
94 public final short shortValue()
95 {
96 return (short) _value;
97 }
98
99 /**
100 * increase by i
101 * @param i the value to increase
102 */
103 public void inc(double i)
104 {
105 _value += i;
106 }
107
108 /**
109 * decrease by i
110 * @param i the value to decrease
111 */
112 public void dec(double i)
113 {
114 _value -= i;
115 }
116
117 /**
118 * {@inheritDoc}
119 */
120 public String toString()
121 {
122 return String.valueOf(_value);
123 }
124 }
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 package org.onemind.commons.java.lang;
20
21 /**
22 * A mutable float
23 * @author TiongHiang Lee (thlee@onemindsoft.org)
24 * @version $Id: MutableFloat.java,v 1.3 2004/09/03 13:24:14 thlee Exp $ $Name: $
25 */
26 public class MutableFloat extends Number
27 {
28
29 /** the float value * */
30 private float _value;
31
32 /**
33 * {@inheritDoc}
34 * @param l the float value
35 */
36 public MutableFloat(float l)
37 {
38 _value = l;
39 }
40
41 /**
42 * Set the float value
43 * @param l the value
44 */
45 public final void set(float l)
46 {
47 _value = l;
48 }
49
50 /**
51 * {@inheritDoc}
52 */
53 public final byte byteValue()
54 {
55 return (byte) _value;
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 public final double doubleValue()
62 {
63 return (double) _value;
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 public final float floatValue()
70 {
71 return _value;
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 public final int intValue()
78 {
79 return (int) _value;
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 public final long longValue()
86 {
87 return (long) _value;
88 }
89
90 /**
91 * {@inheritDoc}
92 */
93 public final short shortValue()
94 {
95 return (short) _value;
96 }
97
98 /**
99 * increase by i
100 * @param i the value to increase
101 */
102 public void inc(float i)
103 {
104 _value += i;
105 }
106
107 /**
108 * decrease by i
109 * @param i the value to decrease
110 */
111 public void dec(float i)
112 {
113 _value -= i;
114 }
115
116 /**
117 * {@inheritDoc}
118 */
119 public String toString()
120 {
121 return String.valueOf(_value);
122 }
123 }
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 package org.onemind.commons.java.lang;
20
21 /**
22 * An mutable integer
23 * @author TiongHiang Lee (thlee@onemindsoft.org)
24 * @version $Id: MutableInteger.java,v 1.3 2004/09/03 13:24:14 thlee Exp $ $Name: $
25 */
26 public class MutableInteger extends Number
27 {
28
29 /** the integer value * */
30 private int _value;
31
32 /**
33 * {@inheritDoc}
34 * @param l the int value
35 */
36 public MutableInteger(int l)
37 {
38 _value = l;
39 }
40
41 /**
42 * Set the value
43 * @param l the int value
44 */
45 public final void set(int l)
46 {
47 _value = l;
48 }
49
50 /**
51 * {@inheritDoc}
52 */
53 public final byte byteValue()
54 {
55 return (byte) _value;
56 }
57
58 /**
59 * {@inheritDoc}
60 */
61 public final double doubleValue()
62 {
63 return (double) _value;
64 }
65
66 /**
67 * {@inheritDoc}
68 */
69 public final float floatValue()
70 {
71 return (float) _value;
72 }
73
74 /**
75 * {@inheritDoc}
76 */
77 public final int intValue()
78 {
79 return _value;
80 }
81
82 /**
83 * {@inheritDoc}
84 */
85 public final long longValue()
86 {
87 return (long) _value;
88 }
89
90 /**
91 * {@inheritDoc}
92 */
93 public final short shortValue()
94 {
95 return (short) _value;
96 }
97
98 /**
99 * increase by i
100 * @param i the value to increase
101 */
102 public void inc(int i)
103 {
104 _value += i;
105 }
106
107 /**
108 * decrease by i
109 * @param i the value to decrease
110 */
111 public void dec(int i)
112 {
113 _value -= i;
114 }
115
116 /**
117 * {@inheritDoc}
118 */
119 public String toString()
120 {
121 return String.valueOf(_value);
122 }
123 }
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.lang;
21
22 /**
23 * An mutable long
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: MutableLong.java,v 1.3 2004/09/03 13:24:14 thlee Exp $ $Name: $
26 */
27 public class MutableLong extends Number
28 {
29
30 /** the long value * */
31 private long _value;
32
33 /**
34 * {@inheritDoc}
35 * @param l the long value
36 */
37 public MutableLong(long l)
38 {
39 _value = l;
40 }
41
42 /**
43 * Set the long value
44 * @param l the long value
45 */
46 public final void set(long l)
47 {
48 _value = l;
49 }
50
51 /**
52 * {@inheritDoc}
53 */
54 public final byte byteValue()
55 {
56 return (byte) _value;
57 }
58
59 /**
60 * {@inheritDoc}
61 */
62 public final double doubleValue()
63 {
64 return (double) _value;
65 }
66
67 /**
68 * {@inheritDoc}
69 */
70 public final float floatValue()
71 {
72 return (float) _value;
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 public final int intValue()
79 {
80 return (int) _value;
81 }
82
83 /**
84 * {@inheritDoc}
85 */
86 public final long longValue()
87 {
88 return _value;
89 }
90
91 /**
92 * {@inheritDoc}
93 */
94 public final short shortValue()
95 {
96 return (short) _value;
97 }
98
99 /**
100 * increase by i
101 * @param i the value to increase
102 */
103 public void inc(long i)
104 {
105 _value += i;
106 }
107
108 /**
109 * decrease by i
110 * @param i the value to decrease
111 */
112 public void dec(long i)
113 {
114 _value -= i;
115 }
116
117 /**
118 * {@inheritDoc}
119 */
120 public String toString()
121 {
122 return String.valueOf(_value);
123 }
124 }
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.lang;
21
22 /**
23 * An mutable short
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: MutableShort.java,v 1.3 2004/09/03 13:24:14 thlee Exp $ $Name: $
26 */
27 public class MutableShort extends Number
28 {
29
30 /** the long value * */
31 private short _value;
32
33 /**
34 * {@inheritDoc}
35 * @param l the long value
36 */
37 public MutableShort(short l)
38 {
39 _value = l;
40 }
41
42 /**
43 * Set the short value
44 * @param l the short value
45 */
46 public final void set(short l)
47 {
48 _value = l;
49 }
50
51 /**
52 * {@inheritDoc}
53 */
54 public final byte byteValue()
55 {
56 return (byte) _value;
57 }
58
59 /**
60 * {@inheritDoc}
61 */
62 public final double doubleValue()
63 {
64 return (double) _value;
65 }
66
67 /**
68 * {@inheritDoc}
69 */
70 public final float floatValue()
71 {
72 return _value;
73 }
74
75 /**
76 * {@inheritDoc}
77 */
78 public final int intValue()
79 {
80 return (int) _value;
81 }
82
83 /**
84 * {@inheritDoc}
85 */
86 public final long longValue()
87 {
88 return (long) _value;
89 }
90
91 /**
92 * {@inheritDoc}
93 */
94 public final short shortValue()
95 {
96 return (short) _value;
97 }
98
99 /**
100 * increase by i
101 * @param i the value to increase
102 */
103 public void inc(short i)
104 {
105 _value += i;
106 }
107
108 /**
109 * decrease by i
110 * @param i the value to decrease
111 */
112 public void dec(short i)
113 {
114 _value -= i;
115 }
116
117 /**
118 * {@inheritDoc}
119 */
120 public String toString()
121 {
122 return String.valueOf(_value);
123 }
124 }
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.lang;
21
22 /**
23 * Represent a Null object
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: Null.java,v 1.2 2004/08/26 12:33:17 thlee Exp $ $Name: $
26 */
27 public final class Null
28 {
29
30 /**
31 * The instance
32 */
33 public static final Null instance = new Null();
34
35 /**
36 * {@inheritDoc}
37 */
38 private Null()
39 {
40 }
41 }
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.lang.ref;
21
22 import java.util.*;
23 import java.lang.ref.*;
24 /**
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: SoftHashMap.java,v 1.1 2004/10/23 15:24:35 thlee Exp $ $Name: $
27 * Credits: Article by Heinz Kabutz at http://archive.devx.com/java/free/articles/Kabutz01/Kabutz01-1.asp
28 */
29 public class SoftHashMap extends AbstractMap
30 {
31
32 /** We define our own subclass of SoftReference which contains
33 not only the value but also the key to make it easier to find
34 the entry in the HashMap after it's been garbage collected. */
35 private static class SoftValue extends SoftReference
36 {
37 private final Object key; // always make data member final
38
39 /** Did you know that an outer class can access private data
40 members and methods of an inner class? I didn't know that!
41 I thought it was only the inner class who could access the
42 outer class's private information. An outer class can also
43 access private members of an inner class inside its inner
44 class. */
45 private SoftValue(Object k, Object key, ReferenceQueue q)
46 {
47 super(k, q);
48 this.key = key;
49 }
50 }
51
52 /** The internal HashMap that will hold the SoftReference. */
53 private final Map hash = new HashMap();
54
55 /** The number of "hard" references to hold internally. */
56 private final int HARD_REF_SIZE;
57
58 /** The FIFO list of hard references, order of last access. */
59 private final LinkedList hardRefCache;
60
61 /** Reference queue for cleared SoftReference objects. */
62 private final ReferenceQueue queue = new ReferenceQueue();
63
64 /**
65 * Constructor
66 */
67 public SoftHashMap()
68 {
69 this(0);
70 }
71
72 /**
73 * Constructor
74 * @param hardSize the hard reference size to maintain
75 */
76 public SoftHashMap(int hardSize)
77 {
78 HARD_REF_SIZE = hardSize;
79 if (HARD_REF_SIZE>0)
80 {
81 hardRefCache = new LinkedList();
82 } else
83 {
84 hardRefCache = null;
85 }
86 }
87
88 public Object get(Object key)
89 {
90 Object result = null;
91 // get the SoftReference represented by that key
92 SoftReference soft_ref = (SoftReference) hash.get(key);
93 if (soft_ref != null)
94 {
95 // From the SoftReference we get the value, which can be
96 // null if it was not in the map, or it was removed in
97 // the processQueue() method defined below
98 result = soft_ref.get();
99 if (result == null)
100 {
101 // If the value has been garbage collected, remove the
102 // entry from the HashMap.
103 hash.remove(key);
104 } else
105 {
106 if (HARD_REF_SIZE>0)
107 {
108 // We now add this object to the beginning of the hard
109 // reference queue. One reference can occur more than
110 // once, because lookups of the FIFO queue are slow, so
111 // we don't want to search through it each time to remove
112 // duplicates.
113 hardRefCache.addFirst(result);
114 if (hardRefCache.size() > HARD_REF_SIZE)
115 {
116 // Remove the last entry if list longer than HARD_SIZE
117 hardRefCache.removeLast();
118 }
119 }
120 }
121 }
122 return result;
123 }
124
125 /**
126 * Go through the ReferenceQueue and remove garbage
127 * collected SoftValue objects from the HashMap
128 */
129 private void _cleanCollectedValues()
130 {
131 SoftValue sv;
132 while ((sv = (SoftValue) queue.poll()) != null)
133 {
134 hash.remove(sv.key); // we can access private data!
135 }
136 }
137
138 /**
139 * Here we put the key, value pair into the HashMap using
140 * a SoftValue object.
141 */
142 public Object put(Object key, Object value)
143 {
144 _cleanCollectedValues(); // throw out garbage collected values first
145 return hash.put(key, new SoftValue(value, key, queue));
146 }
147
148 /**
149 * {@inheritDoc}
150 */
151 public Object remove(Object key)
152 {
153 _cleanCollectedValues(); // throw out garbage collected values first
154 return hash.remove(key);
155 }
156
157 /**
158 * {@inheritDoc}
159 */
160 public void clear()
161 {
162 if (HARD_REF_SIZE>0)
163 {
164 hardRefCache.clear();
165 }
166 _cleanCollectedValues(); // throw out garbage collected values
167 hash.clear();
168 }
169
170 /**
171 * {@inheritDoc}
172 */
173 public int size()
174 {
175 _cleanCollectedValues(); // throw out garbage collected values first
176 return hash.size();
177 }
178
179 /**
180 * {@inheritDoc}
181 */
182 public Set entrySet()
183 {
184 // no, no, you may NOT do that!!! GRRR
185 throw new UnsupportedOperationException();
186 }
187 }
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.lang.ref;
21
22 /**
23 * ValueRef is a passable reference to a value
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 */
26
27 public interface ValueRef
28 {
29 public Object getValue();
30
31 public void setValue(Object obj);
32 }
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.lang.reflect;
21
22 import java.util.*;
23 import java.util.logging.Level;
24 import java.util.logging.Logger;
25 import org.onemind.commons.java.datastructure.LookupCache;
26 /**
27 * A class lookup cache can lookup non-fully-qualified name classes for a given set
28 * of packages and will cache the lookup for later use. For example, <br>
29 *
30 * <pre>
31 * ClassLookupCache cache = new ClassLookupCache();
32 * cache.addPackage("*"); //default package
33 * cache.addPackage("java.io.*");
34 *
35 * Class c = cache.getClass("File"); //c = java.io.File
36 * c = cache.getClass("File1"); //c = null
37 * </pre>
38 *
39 * NOTE:
40 * 1. The cache is static for all instances of the lookup cache.
41 * 2. The packages is instance specific
42 * 3. It will cache only positive and negative response of fully qualified name thus
43 * lookup of non-fully-qualified has some performance hit, but for the sake of correctness
44 *
45 *
46 * @author TiongHiang Lee (thlee@onemindsoft.org)
47 * @version $Id: ClassLookupCache.java,v 1.6 2006/10/29 17:02:38 thlee Exp $ $Name: $
48 */
49 public class ClassLookupCache extends LookupCache
50 {
51
52 /** the packages * */
53 private final HashSet _packages = new LinkedHashSet();
54
55 /** the logger * */
56 private static final Logger _logger = Logger.getLogger(ClassLookupCache.class.getName());
57
58 /**
59 * {@inheritDoc}
60 */
61 public ClassLookupCache()
62 {
63 }
64
65 /**
66 * Add a new package.
67 * @param packageName the package name
68 */
69 public void addImport(String importName)
70 {
71 if (importName==null){
72 throw new IllegalArgumentException("Package name must not be null");
73 }
74 _packages.add(importName);
75 clearNegCache();
76 }
77
78 /**
79 * Get the class given by the fully-qualified or non-fully qualified java class name
80 * @param className the class name
81 * @return the class or null
82 */
83 public Class getClass(String className)
84 {
85 if (className.indexOf('.') == -1)
86 { //not fully qualified name
87 Iterator it = _packages.iterator();
88 Class c = null;
89 while (it.hasNext())
90 {
91 String importName = (String) it.next();
92 String fullName = null;
93 int idx = importName.indexOf("*");
94 if (idx==-1){ //importName is a class name
95 if (importName.endsWith("." + className) || importName.equals(className)){
96 fullName = importName;
97 } else { //don't bother
98 continue;
99 }
100 } else {
101 fullName = importName.substring(0, idx) + className;
102 }
103 if (_logger.isLoggable(Level.FINEST))
104 {
105 _logger.finest("Looking up class " + fullName);
106 }
107 c = (Class) lookup(fullName);
108 if (c != null)
109 {
110 return c;
111 }
112 }
113 return null;
114 } else
115 {
116 return (Class) lookup(className);
117 }
118 }
119
120 /**
121 * Produce the class given the key {@inheritDoc}
122 */
123 public Object produce(Object key)
124 {
125 String className = (String) key;
126 Class c = null;
127 //first trial
128 try
129 {
130 c = Class.forName(className);
131 if (_logger.isLoggable(Level.FINEST))
132 {
133 _logger.finest("Lookup class " + key + " successful");
134 //otherwise the ClassNotFoundException must have been throwned
135 }
136 } catch (Exception e)
137 {
138 if (_logger.isLoggable(Level.FINEST))
139 {
140 _logger.finest("Lookup class " + key + " failed");
141 }
142 }
143 return c;
144 }
145
146 /**
147 * Get all the import packages in this lookup cache.
148 * @return the packages
149 */
150 public Set getPackages()
151 {
152 return Collections.unmodifiableSet(_packages);
153 }
154
155 /**
156 * {@inheritDoc}
157 */
158 protected void clearNegCache()
159 {
160 super.clearNegCache();
161 }
162
163 /**
164 * {@inheritDoc}
165 */
166 protected boolean isInCache(Object o)
167 {
168 return super.isInCache(o);
169 }
170
171 /**
172 * {@inheritDoc}
173 */
174 protected boolean isInNegCache(Object o)
175 {
176 return super.isInNegCache(o);
177 }
178
179 /**
180 * {@inheritDoc}
181 */
182 protected void setDoNegativeCache(boolean b)
183 {
184 super.setDoNegativeCache(b);
185 }
186 }
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.lang.reflect;
21
22 import java.lang.reflect.*;
23 import java.util.*;
24 import java.util.logging.Level;
25 import java.util.logging.Logger;
26 import org.onemind.commons.java.datastructure.Scoreable;
27 import org.onemind.commons.java.util.StringUtils;
28 /**
29 * Reflection related utilities
30 * @author TiongHiang Lee (thlee@onemindsoft.org)
31 * @version $Id: ReflectUtils.java,v 1.12 2006/08/01 23:57:03 thlee Exp $ $Name: $
32 */
33 public final class ReflectUtils
34 {
35
36 /** the logger * */
37 private static final Logger _logger = Logger.getLogger(ReflectUtils.class.getName());
38
39 /** the lookup cache * */
40 private static final Map _classCache = new HashMap();
41
42 /** the method cache **/
43 private static final Map _methodCache = new HashMap();
44
45 /** class caching setting **/
46 private static boolean _classCaching = true;
47
48 /** method caching setting **/
49 private static boolean _methodCaching = true;
50
51 /** keep a primitive class and their compatible types **/
52 private static final Map WIDENABLES = new HashMap();
53 static
54 {
55 Object[][] primitiveWideningMap = new Object[][]{
56 {Boolean.TYPE, new Object[]{Boolean.TYPE, Boolean.class}},
57 {Boolean.class, new Object[]{Boolean.TYPE, Boolean.class}},
58 {Byte.TYPE, new Object[]{Byte.TYPE, Byte.class, Short.class, Short.TYPE, Integer.class, Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
59 {Byte.class, new Object[]{Byte.TYPE, Byte.class, Short.class, Short.TYPE, Integer.class, Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
60 {Short.TYPE, new Object[]{Short.TYPE, Short.class, Integer.class, Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
61 {Short.class, new Object[]{Short.TYPE, Short.class, Integer.class, Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
62 {Character.TYPE, new Object[]{Character.TYPE, Character.class, Integer.class, Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
63 {Character.class, new Object[]{Character.TYPE, Character.class, Integer.class, Integer.TYPE, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
64 {Integer.TYPE, new Object[]{Integer.TYPE, Integer.class, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
65 {Integer.class, new Object[]{Integer.TYPE, Integer.class, Long.class, Long.TYPE, Float.class, Float.TYPE, Double.class, Double.TYPE}},
66 {Long.TYPE, new Object[]{Long.TYPE, Long.class, Float.class, Float.TYPE, Double.class, Double.TYPE}},
67 {Long.class, new Object[]{Long.TYPE, Long.class, Float.class, Float.TYPE, Double.class, Double.TYPE}},
68 {Float.TYPE, new Object[]{Float.TYPE, Float.class, Double.class, Double.TYPE}},
69 {Float.class, new Object[]{Float.TYPE, Float.class, Double.class, Double.TYPE}},
70 {Double.TYPE, new Object[]{Double.TYPE, Double.class}},
71 {Double.class, new Object[]{Double.TYPE, Double.class}}};
72
73 for (int i = 0; i < primitiveWideningMap.length; i++)
74 {
75 WIDENABLES.put(primitiveWideningMap[i][0], Arrays.asList((Object[]) primitiveWideningMap[i][1]));
76 }
77 }
78
79 /**
80 * The method key
81 */
82 private static class MethodKey
83 {
84
85 /** the name **/
86 private String _name;
87
88 /** the class **/
89 private Class _clazz;
90
91 /** the arguments **/
92 private Class[] _args;
93
94 /** the hash code **/
95 private int _hashCode;
96
97 /**
98 * Constructor
99 * @param clazz the class
100 * @param name the name
101 * @param args the arguments
102 */
103 public MethodKey(Class clazz, String name, Class[] args)
104 {
105 _clazz = clazz;
106 _name = name;
107 _args = args;
108 _hashCode = _clazz.hashCode() + _name.hashCode();
109 }
110
111 /**
112 * {@inheritDoc}
113 */
114 public int hashCode()
115 {
116 return _hashCode;
117 }
118
119 /**
120 * {@inheritDoc}
121 */
122 public boolean equals(Object obj)
123 {
124 if (obj instanceof MethodKey)
125 {
126 MethodKey key = (MethodKey) obj;
127 return _clazz.equals(key._clazz) && _name.equals(key._name) && Arrays.equals(_args, key._args);
128 } else
129 {
130 throw new IllegalArgumentException("Cannot compare " + this + " to " + obj);
131 }
132 }
133 }
134
135 /**
136 * {@inheritDoc}
137 */
138 private ReflectUtils()
139 {
140 };
141
142 /**
143 * Construct the argument type class array from a list of arg objects
144 * @param args the arguments
145 * @return the class array
146 * @todo decide what to do with null value arguments and what to do with isCompatibleCheck
147 * TODO decide what to do with null value arguments and what to do with isCompatibleCheck
148 */
149 public static final Class[] toArgTypes(Object[] args)
150 {
151 if (args == null)
152 {
153 args = new Object[0];
154 }
155 Class[] argTypes = new Class[args.length];
156 for (int i = 0; i < args.length; i++)
157 {
158 if (args[i] != null)
159 {
160 argTypes[i] = args[i].getClass();
161 }
162 }
163 return argTypes;
164 }
165
166 /**
167 * Get the class
168 * @param name the name of the class
169 * @return the class
170 * @throws ClassNotFoundException if the class cannot be found
171 */
172 public static final Class getClass(String name) throws ClassNotFoundException
173 {
174 if (_classCaching && _classCache.containsKey(name))
175 {
176 Class c = (Class) _classCache.get(name);
177 if (c == null)
178 {
179 throw new ClassNotFoundException("Class " + name + " not found");
180 } else
181 {
182 return c;
183 }
184 } else
185 {
186 Class c = null;
187 try
188 {
189 c = Class.forName(name);
190 return c;
191 } finally
192 {
193 if (_classCaching)
194 {
195 _classCache.put(name, c);
196 }
197 }
198 }
199 }
200
201 /**
202 * Get the constructor of the type given the arguments to the constructor
203 * @param type the type
204 * @param args the arguments
205 * @return the constructor
206 * @throws NoSuchMethodException if the constructor cannot be found
207 */
208 public static final Constructor getConstructor(Class type, Object[] args) throws NoSuchMethodException
209 {
210 if (args == null)
211 {
212 args = new Object[0];
213 }
214 Class[] argTypes = toArgTypes(args);
215 Constructor c = null;
216 if (_methodCaching) //look in cache
217 {
218 c = (Constructor) _methodCache.get(new MethodKey(type, "$Constructor", argTypes));
219 if (c != null)
220 {
221 return c;
222 }
223 }
224 try
225 {
226 //first trial
227 if (_logger.isLoggable(Level.FINEST))
228 {
229 _logger.finest("Looking for constructor for " + type.getName() + "(" + StringUtils.concat(argTypes, ",") + ")");
230 }
231 c = type.getConstructor(argTypes);
232 } catch (NoSuchMethodException e)
233 {
234 c = searchConstructor(type, argTypes);
235 }
236 if (c == null)
237 {
238 throw new NoSuchMethodException("Constructor not found for class " + toMethodString(type.getName(), args));
239 } else if (_methodCaching)
240 {
241 _methodCache.put(new MethodKey(type, "$Constructor", argTypes), c);
242 }
243 return c;
244 }
245
246 /**
247 * To the method representation string e.g. toString()
248 * @param methodName the method
249 * @param args the arguments
250 * @return the method representation string
251 */
252 public static final String toMethodString(String methodName, Object[] args)
253 {
254 StringBuffer sb = new StringBuffer(methodName);
255 sb.append("(");
256 if (args != null)
257 {
258 sb.append(StringUtils.concat(args, ","));
259 }
260 sb.append(")");
261 return sb.toString();
262 }
263
264 /**
265 * Search for a particular constructor based on arg types classes
266 * @param type the type
267 * @param argTypes the argument types
268 * @return the constructor
269 */
270 public static final Constructor searchConstructor(Class type, Class[] argTypes)
271 {
272 if (_logger.isLoggable(Level.FINEST))
273 {
274 _logger.finest("Searching for constructor for " + type.getName());
275 }
276 Constructor[] constructors = type.getConstructors();
277 TreeSet scoreboard = new TreeSet();
278 for (int i = 0; i < constructors.length; i++)
279 {
280 Class[] types = constructors[i].getParameterTypes();
281 if (_logger.isLoggable(Level.FINEST))
282 {
283 _logger.finest("trying arg types " + StringUtils.concat(types, ","));
284 }
285 int score = computeCompatibalityScore(types, argTypes);
286 if (score > 0)
287 {
288 scoreboard.add(new Scoreable(score, constructors[i]));
289 }
290 }
291 if (scoreboard.size() > 0)
292 {
293 return (Constructor) ((Scoreable) scoreboard.last()).getObject();
294 } else
295 {
296 return null;
297 }
298 }
299
300 /**
301 * Return whether the argument objects is compatible with the argument types specification
302 * @param types the argument types
303 * @param args the arguments
304 * @return true if compatible
305 */
306 public static final boolean isCompatible(Class[] types, Object[] args)
307 {
308 return computeCompatibalityScore(types, toArgTypes(args)) > 0;
309 }
310
311 public static final boolean isCompatible(Class[] types, Class[] argTypes)
312 {
313 return computeCompatibalityScore(types, argTypes) > 0;
314 }
315
316 /**
317 * Return whether the types of arguments is compatible with the argument type spec of a method
318 * @param methodTypes the argument type spec of a method
319 * @param argTypes the argument type
320 * @return true if compatible
321 */
322 public static final int computeCompatibalityScore(Class[] methodTypes, Class[] argTypes)
323 {
324 int score = 0;
325 if ((methodTypes == null) || (methodTypes.length == 0))
326 {
327 if ((argTypes == null) || (argTypes.length == 0))
328 {
329 score = 1;
330 }
331 } else if (argTypes != null && methodTypes.length == argTypes.length)
332 {
333 for (int i = 0; i < methodTypes.length; i++)
334 {
335 if (_logger.isLoggable(Level.FINEST))
336 {
337 _logger.finest("Comparing " + methodTypes[i] + " to " + argTypes[i]);
338 }
339 if (methodTypes[i] == argTypes[i])
340 {
341 score += 2;
342 }else if (argTypes[i] == null)
343 {
344 if (methodTypes[i].isPrimitive()){
345 score = 0;
346 break;
347 } else {
348 score += 1; //assume underlying args is null which is allowable
349 }
350 } else if (WIDENABLES.containsKey(argTypes[i]))
351 {//maybe it can be widen
352
353 int thisScore = computeWideningScore(methodTypes[i], argTypes[i]);
354 if (thisScore == 0)
355 {
356 score = 0;
357 break;
358 } else
359 {
360 score += thisScore;
361 }
362 } else if (methodTypes[i].isAssignableFrom(argTypes[i]))
363 {
364 score += 1;
365 } else {
366 score = 0;
367 break;
368 }
369 }
370 }
371 return score;
372 }
373
374 /**
375 * Create a new instance of the class type with the arguments to constructor
376 * @param type the type
377 * @param args the argument
378 * @return the new instance
379 * @throws IllegalAccessException if there's access problem
380 * @throws InstantiationException if there's instantiation problem
381 * @throws InvocationTargetException if there's target exception
382 * @throws NoSuchMethodException if there's no such constructor
383 */
384 public static final Object newInstance(Class type, Object[] args) throws IllegalAccessException, InstantiationException,
385 InvocationTargetException, NoSuchMethodException
386 {
387 if (args == null)
388 {
389 args = new Object[0];
390 }
391 Constructor c = getConstructor(type, args);
392 if (c != null)
393 {
394 return c.newInstance(args);
395 } else
396 {
397 throw new NoSuchMethodException("Constructor not found for " + type);
398 }
399 }
400
401 /**
402 * Invoke a named method on the object using the arguments
403 * @param o the object
404 * @param methodName the name of the method
405 * @param args the arguments
406 * @return the object return by the invocation
407 * @throws NoSuchMethodException if there's no such method
408 * @throws IllegalAccessException if there's access problem
409 * @throws InvocationTargetException if there's target problem
410 * @todo decide if is necessary to check for declaring class before invoke
411 */
412 public static final Object invoke(Object o, String methodName, Object[] args) throws NoSuchMethodException,
413 IllegalAccessException, InvocationTargetException
414 {
415 if (args == null)
416 {
417 args = new Object[0];
418 }
419 Method m = null;
420 if (o instanceof Class)
421 {
422 try
423 {
424 //try to get static method
425 m = getMethod((Class) o, methodName, args);
426 } catch (NoSuchMethodException e)
427 {
428 //when user trying to get the "class instance" method
429 m = getMethod(o.getClass(), methodName, args);
430 }
431 } else
432 {
433 m = getMethod(o.getClass(), methodName, args);
434 }
435 if (m != null)
436 {
437 if (_logger.isLoggable(Level.FINEST))
438 {
439 _logger.finest("Invoking " + m + " on " + o);
440 }
441 return m.invoke(o, args);
442 } else
443 {
444 throw new NoSuchMethodException("There's no method " + toMethodString(methodName, args) + " for " + m);
445 }
446 }
447
448 /**
449 * Resolve the method from the interfaces
450 * @param c the class
451 * @param methodName the method
452 * @param argTypes the arg types
453 * @return the method or null
454 * @todo decide if this method is needed
455 */
456 public static final Method getInterfaceMethod(Class[] c, String methodName, Class[] argTypes)
457 {
458 //TODO: decide if needed
459 return null;
460 }
461
462 /**
463 * Get a named method of class type with the argument type compatible with the argument passed in.
464 *
465 * @param type the class
466 * @param methodName the method name
467 * @param args the arguments
468 * @return the method
469 * @throws NoSuchMethodException if the method cannot be found
470 */
471 public static final Method getMethod(Class type, String methodName, Object[] args) throws NoSuchMethodException
472 {
473 Method m = null;
474 if (_logger.isLoggable(Level.FINEST))
475 {
476 _logger.finest("Finding method " + toMethodString(methodName, args) + " of " + type);
477 }
478 if (args == null)
479 {
480 args = new Object[0];
481 }
482 Class[] argTypes = toArgTypes(args);
483 return getMethod(type, methodName, argTypes);
484 }
485
486 /**
487 * Get a named method of class type with the argument type compatible with the argument passed in.
488 *
489 * @param type the class
490 * @param methodName the method name
491 * @param args the arguments
492 * @return the method
493 * @throws NoSuchMethodException if the method cannot be found
494 */
495 public static final Method getMethod(Class type, String methodName, Class[] argTypes) throws NoSuchMethodException
496 {
497 Method m;
498 if (_methodCaching) //look in cache
499 {
500 m = (Method) _methodCache.get(new MethodKey(type, methodName, argTypes));
501 if (m != null)
502 {
503 return m;
504 }
505 }
506 try
507 {
508 //first trial
509 m = type.getMethod(methodName, argTypes);
510 if (_logger.isLoggable(Level.FINEST))
511 {
512 _logger.finest("Found using reflection");
513 }
514 } catch (NoSuchMethodException nme)
515 {
516 if (_logger.isLoggable(Level.FINEST))
517 {
518 _logger.finest("Failed using reflection: " + nme.getMessage() + ". Search for method.");
519 }
520 m = searchMethod(type, methodName, argTypes);
521 }
522 if (m != null)
523 {
524 if (_methodCaching)
525 {
526 _methodCache.put(new MethodKey(type, methodName, argTypes), m);
527 }
528 if (!m.isAccessible())
529 {
530 m.setAccessible(true);
531 }
532 } else
533 {
534 throw new NoSuchMethodException("Method " + type.getName() + "." + toMethodString(methodName, argTypes) + " not found.");
535 }
536 return m;
537 }
538
539 /**
540 * Search a named method of class type through the class's hierachy
541 * @param type the class
542 * @param methodName the method name
543 * @param argTypes the argument types
544 * @return the method
545 */
546 private static final Method searchMethod(Class type, String methodName, Class[] argTypes)
547 {
548 TreeSet scoreboard = new TreeSet();
549 Method[] methods = type.getMethods();
550 for (int i = 0; i < methods.length; i++)
551 {
552 Method m = methods[i];
553 if (_logger.isLoggable(Level.FINEST))
554 {
555 _logger.finest("Checking compatibility with " + m);
556 }
557 if (m.getName().equals(methodName))
558 {
559 int score = computeCompatibalityScore(m.getParameterTypes(), argTypes);
560 if (score > 0)
561 {
562 scoreboard.add(new Scoreable(score, methods[i]));
563 }
564 }
565 }
566 if (scoreboard.size() > 0)
567 {
568 return (Method) ((Scoreable) scoreboard.last()).getObject();
569 }
570 return null;
571 }
572
573 /**
574 * Set the classCaching
575 * @param caching true to turn on class caching
576 */
577 protected static final void setClassCaching(boolean caching)
578 {
579 _classCaching = caching;
580 }
581
582 /**
583 * Set the _methodCaching
584 * @param caching true to turn on method caching
585 */
586 protected static final void setMethodCaching(boolean caching)
587 {
588 _methodCaching = caching;
589 }
590
591 /**
592 * Return whether a given object is a primitive or compatible (through unwrapping and widening) instance of primitiveClass
593 * @param primitiveClass the primitive class
594 * @param obj the object
595 * @return true if is instance
596 */
597 public static final boolean isPrimitiveInstance(Class primitiveClass, Object obj)
598 {
599 if (!primitiveClass.isPrimitive())
600 {
601 throw new IllegalArgumentException(primitiveClass + " is not primitive type ");
602 }
603 if (obj == null)
604 {
605 return false;
606 } else
607 {
608 return isPrimitiveCompatible(primitiveClass, obj.getClass());
609 }
610 }
611
612 /**
613 * Check if class c can be widen to targetClass and return the score.
614 * Return 2 if c==primitiveClass, 1 if c can be widened, or 0 if c cannot be widened.
615 * @param primitiveClass
616 * @param c
617 * @return
618 */
619
620 private static final int computeWideningScore(Class primitiveClass, Class c)
621 {
622 //check if c can be widen to primitiveClass
623 List set = (List) WIDENABLES.get(c);
624 int i = set.indexOf(primitiveClass);
625 if (i==-1){
626 return 0;
627 } else if (i<2){
628 return 2; //exact match
629 } else {
630 return 1;
631 }
632 }
633
634 /**
635 * Return true if primitiveClass and clazz is both primitive and clazz is primitive compatible with primitiveClass
636 * using java rules (unwrapping or widening)
637 * @param primitiveClass
638 * @param clazz
639 * @return
640 */
641 public static final boolean isPrimitiveCompatible(Class primitiveClass, Class clazz)
642 {
643 return computeWideningScore(primitiveClass, clazz) > 0;
644 }
645 }
0
1 package org.onemind.commons.java.pattern;
2
3 import java.lang.reflect.Method;
4 import org.onemind.commons.java.datastructure.InheritableValueMap;
5 import org.onemind.commons.java.lang.reflect.ReflectUtils;
6 /**
7 * An abstract implementation of visitor that is extensible for handling
8 * different kind of object nodes by simple adding more methods. The subclass need to
9 * set up for handlers of node type in the constructor.
10 *
11 * @author TiongHiang Lee (thlee@onemindsoft.org)
12 * @version $Id: DynamicVisitor.java,v 1.2 2004/10/31 16:02:08 thlee Exp $ $Name: $
13 */
14 public abstract class DynamicVisitor
15 {
16
17 /** the object array class **/
18 private static Class OBJECT_ARRAY_CLASS = new Object[0].getClass();
19
20 /**
21 * The handler
22 * @author TiongHiang Lee (thlee@onemindsoft.org)
23 * @version $Id: DynamicVisitor.java,v 1.2 2004/10/31 16:02:08 thlee Exp $ $Name: $
24 */
25 public static interface NodeHandler
26 {
27
28 /**
29 * Handle node
30 * @param node
31 * @param data
32 */
33 public Object handleNode(Object node, Object[] data) throws Exception;
34 }
35
36 /**
37 * A handler use reflection to invoke given method for visiting
38 */
39 protected class MethodNodeHandler implements NodeHandler
40 {
41
42 /** the method **/
43 private Method _method;
44
45 /**
46 * Constructor
47 * @param methodName the method name
48 */
49 public MethodNodeHandler(Method method)
50 {
51 _method = method;
52 }
53
54 /**
55 * {@inheritDoc}
56 */
57 public Object handleNode(Object node, Object[] data) throws Exception
58 {
59 Object[] args = {node, data};
60 return _method.invoke(DynamicVisitor.this, args);
61 }
62 }
63
64 /** contains the handlers for different kind of nodese **/
65 private final InheritableValueMap _handlers = new InheritableValueMap();
66
67 /**
68 * Constructor
69 */
70 public DynamicVisitor()
71 {
72 initNodeHandlers();
73 }
74
75 /**
76 * Initialize the node handlers
77 */
78 protected abstract void initNodeHandlers();
79
80 /**
81 * Add node handler
82 * @param type the type
83 * @param handler the handler
84 */
85 protected void addNodeHandler(Class type, NodeHandler handler)
86 {
87 _handlers.put(type, handler);
88 }
89
90 /**
91 * Add MethodNodeHandler using the given method name
92 * throws RuntimeException if the method cannot be found.
93 * @param type the type
94 * @param methodName the method name
95 */
96 protected void addMethodNodeHandler(Class type, String methodName)
97 {
98 try
99 {
100 Class args[] = {type, new Object[0].getClass()};
101 Method m = ReflectUtils.getMethod(getClass(), methodName, args);
102 _handlers.put(type, new MethodNodeHandler(m));
103 } catch (Exception e)
104 {
105 throw new RuntimeException(e);
106 }
107 }
108
109 /**
110 * The object
111 * @param obj the object
112 * @param args the arguments
113 */
114 public Object visit(Object obj, Object[] args) throws Exception
115 {
116 NodeHandler handler = (NodeHandler) _handlers.resolve(obj.getClass());
117 if (handler != null)
118 {
119 return handler.handleNode(obj, args);
120 } else
121 {
122 throw new IllegalArgumentException("Cannot find handler method for object " + obj);
123 }
124 }
125 }
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.sql;
21
22 /**
23 * A Field contains meta infomration of a field in the database table
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: Field.java,v 1.2 2004/08/26 12:33:18 thlee Exp $ $Name: $
26 */
27 public class Field
28 {
29
30 /** the name * */
31 private String _name;
32
33 /** the sql type * */
34 private int _type;
35
36 /**
37 * create a new field with name <i>name </i> and type <i>type </i>
38 * @param name the name
39 * @param type the type
40 */
41 public Field(String name, int type)
42 {
43 _name = name;
44 _type = type;
45 }
46
47 /**
48 * return the name of the field
49 * @return the name
50 */
51 public String getName()
52 {
53 return _name;
54 }
55
56 /**
57 * get the type of the field
58 * @return the type
59 */
60 public int getType()
61 {
62 return _type;
63 }
64
65 /**
66 * {@inheritDoc}
67 */
68 public String toString()
69 {
70 return "Field:" + _name + ":" + _type;
71 }
72 }
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.sql;
21
22 import java.math.BigDecimal;
23 import java.sql.*;
24 import java.util.*;
25 import java.util.Date;
26 /**
27 * JDBC utilities
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: JdbcUtils.java,v 1.3 2004/10/23 15:25:44 thlee Exp $ $Name: $
30 */
31 public final class JdbcUtils
32 {
33
34 /** map the java classes to jdbc type int * */
35 public static final Map CLASS_TO_TYPE_MAP;
36 static
37 {
38 Map m = new HashMap();
39 m.put(String.class, new Integer(Types.CHAR));
40 m.put(String.class, new Integer(Types.VARCHAR));
41 m.put(String.class, new Integer(Types.LONGVARCHAR));
42 m.put(BigDecimal.class, new Integer(Types.NUMERIC));
43 m.put(Boolean.class, new Integer(Types.BIT));
44 m.put(Boolean.TYPE, new Integer(Types.BIT));
45 m.put(Integer.class, new Integer(Types.INTEGER));
46 m.put(Integer.TYPE, new Integer(Types.INTEGER));
47 m.put(Long.class, new Integer(Types.BIGINT));
48 m.put(Long.TYPE, new Integer(Types.BIGINT));
49 m.put(Float.class, new Integer(Types.REAL));
50 m.put(Float.TYPE, new Integer(Types.REAL));
51 m.put(Double.class, new Integer(Types.DOUBLE));
52 m.put(Double.TYPE, new Integer(Types.DOUBLE));
53 m.put(byte[].class, new Integer(Types.BINARY));
54 m.put(byte[].class, new Integer(Types.VARBINARY));
55 m.put(byte[].class, new Integer(Types.LONGVARBINARY));
56 m.put(Date.class, new Integer(Types.DATE));
57 m.put(Time.class, new Integer(Types.TIME));
58 m.put(Timestamp.class, new Integer(Types.TIMESTAMP));
59 m.put(Clob.class, new Integer(Types.CLOB));
60 m.put(Blob.class, new Integer(Types.BLOB));
61 m.put(Array.class, new Integer(Types.ARRAY));
62 m.put(Struct.class, new Integer(Types.STRUCT));
63 m.put(Ref.class, new Integer(Types.REF));
64 m.put(Class.class, new Integer(Types.JAVA_OBJECT));
65 CLASS_TO_TYPE_MAP = Collections.unmodifiableMap(m);
66 }
67
68 /**
69 * {@inheritDoc}
70 */
71 private JdbcUtils()
72 {
73 }
74
75 /**
76 * Get the MetaData from the resultset
77 * @param rst the result set
78 * @param name the name of metadata to create
79 * @return the metadata
80 * @throws SQLException if there's database problem
81 */
82 public static MetaData getMetaData(ResultSet rst, String name) throws SQLException
83 {
84 return getMetaData(rst.getMetaData(), name);
85 }
86
87 /**
88 * return the MetaData
89 * @param meta the resultset metadata
90 * @param name the name
91 * @return the meta data
92 * @throws SQLException if there's database problem
93 */
94 public static MetaData getMetaData(ResultSetMetaData meta, String name) throws SQLException
95 {
96 MetaData metaData = new MetaData(name);
97 int n = meta.getColumnCount();
98 for (int i = 1; i <= n; i++)
99 {
100 String cname = meta.getColumnName(i);
101 int ctype = meta.getColumnType(i);
102 metaData.addField(new Field(cname, ctype));
103 }
104 return metaData;
105 }
106
107 /**
108 * Return the jdbc type given the java type (based on JDBC spec)
109 * @param c the java class
110 * @return the jdbc type
111 */
112 public static int toJdbcType(Class c)
113 {
114 Integer i = (Integer) CLASS_TO_TYPE_MAP.get(c);
115 if (i != null)
116 {
117 return i.intValue();
118 } else
119 {
120 throw new IllegalArgumentException("Unknown class type" + c);
121 }
122 }
123
124 /**
125 * Return whether a java type is a jdbc type
126 * @param c the class
127 * @return true if it's jdbc type
128 */
129 public static boolean isJdbcType(Class c)
130 {
131 return CLASS_TO_TYPE_MAP.containsKey(c);
132 }
133 }
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 package org.onemind.commons.java.sql;
20
21 import java.util.*;
22 /**
23 * A MetaData contains metadata about a database table
24 * @author TiongHiang Lee (thlee@onemindsoft.org)
25 * @version $Id: MetaData.java,v 1.2 2004/08/26 12:33:18 thlee Exp $ $Name: $
26 */
27 public class MetaData
28 {
29
30 /** the fields * */
31 private Map _fields = new LinkedHashMap();
32
33 /** the name * */
34 private String _name;
35
36 /** the primary key field name * */
37 private String _idFieldName;
38
39 /**
40 * create a MetaData with id <i>id </i>
41 * @param name the name
42 */
43 public MetaData(String name)
44 {
45 this._name = name;
46 }
47
48 /**
49 * create a MetaData with id <i>id </i> and primaryke <i>pj </i>
50 * @param name the name
51 * @param idFieldName the unique identifier field name
52 */
53 public MetaData(String name, String idFieldName)
54 {
55 this(name);
56 _idFieldName = idFieldName;
57 }
58
59 /**
60 * add a new field
61 * @param field the field
62 */
63 public void addField(Field field)
64 {
65 _fields.put(field.getName(), field);
66 }
67
68 /**
69 * get the field with id <i>name </i>
70 * @param name the name
71 * @return the field, or null
72 */
73 public Field getField(String name)
74 {
75 return (Field) _fields.get(name);
76 }
77
78 /**
79 * get the fields in this MetaData
80 * @return Map the map
81 */
82 public Map getFields()
83 {
84 return Collections.unmodifiableMap(_fields);
85 }
86
87 /**
88 * return the id of the MetaData
89 * @return the id
90 */
91 public String getId()
92 {
93 return _name;
94 }
95
96 /**
97 * return the primary key field
98 * @return the id field
99 */
100 public Field getIdField()
101 {
102 return (Field) _fields.get(getIdField());
103 }
104
105 /**
106 * Return the id field name
107 * @return the id field name
108 */
109 public String getIdFieldName()
110 {
111 return _idFieldName;
112 }
113
114 /**
115 * return whether there's a field with id <i>name </i>
116 * @param name the field name
117 * @return true if has the field
118 */
119 public boolean hasField(String name)
120 {
121 return _fields.containsKey(name);
122 }
123
124 /**
125 * set the fields of the MetaData
126 * @param fields the fields
127 */
128 public void setFields(Map fields)
129 {
130 _fields.clear();
131 _fields.putAll(fields);
132 }
133
134 /**
135 * Set the id field name
136 * @param string the id field name
137 */
138 public void setIdFieldName(String string)
139 {
140 _idFieldName = string;
141 }
142 }
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.sql;
21
22 import java.math.BigDecimal;
23 import java.sql.*;
24 import java.util.*;
25 import java.util.Date;
26 /**
27 * May jdbc type to java type
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: TypeMapper.java,v 1.2 2004/08/26 12:33:18 thlee Exp $ $Name: $
30 */
31 public final class TypeMapper
32 {
33
34 /** map the java classes to jdbc type int * */
35 public static final Map CLASS_TO_TYPE_MAP;
36 static
37 {
38 Map m = new HashMap();
39 m.put(String.class, new Integer(Types.CHAR));
40 m.put(String.class, new Integer(Types.VARCHAR));
41 m.put(String.class, new Integer(Types.LONGVARCHAR));
42 m.put(BigDecimal.class, new Integer(Types.NUMERIC));
43 m.put(Boolean.class, new Integer(Types.BIT));
44 m.put(Boolean.TYPE, new Integer(Types.BIT));
45 m.put(Integer.class, new Integer(Types.INTEGER));
46 m.put(Integer.TYPE, new Integer(Types.INTEGER));
47 m.put(Long.class, new Integer(Types.BIGINT));
48 m.put(Long.TYPE, new Integer(Types.BIGINT));
49 m.put(Float.class, new Integer(Types.REAL));
50 m.put(Float.TYPE, new Integer(Types.REAL));
51 m.put(Double.class, new Integer(Types.DOUBLE));
52 m.put(Double.TYPE, new Integer(Types.DOUBLE));
53 m.put(byte[].class, new Integer(Types.BINARY));
54 m.put(byte[].class, new Integer(Types.VARBINARY));
55 m.put(byte[].class, new Integer(Types.LONGVARBINARY));
56 m.put(Date.class, new Integer(Types.DATE));
57 m.put(Time.class, new Integer(Types.TIME));
58 m.put(Timestamp.class, new Integer(Types.TIMESTAMP));
59 m.put(Clob.class, new Integer(Types.CLOB));
60 m.put(Blob.class, new Integer(Types.BLOB));
61 m.put(Array.class, new Integer(Types.ARRAY));
62 m.put(Struct.class, new Integer(Types.STRUCT));
63 m.put(Ref.class, new Integer(Types.REF));
64 m.put(Class.class, new Integer(Types.JAVA_OBJECT));
65 CLASS_TO_TYPE_MAP = Collections.unmodifiableMap(m);
66 }
67
68 /**
69 * Return the jdbc type given the java type (based on JDBC spec)
70 * @param c the java class
71 * @return the jdbc type
72 */
73 public static int toJdbcType(Class c)
74 {
75 Integer i = (Integer) CLASS_TO_TYPE_MAP.get(c);
76 if (i != null)
77 {
78 return i.intValue();
79 } else
80 {
81 throw new IllegalArgumentException("Unknown class type" + c);
82 }
83 }
84
85 /**
86 * Return whether a java type is a jdbc type
87 * @param c the class
88 * @return true if it's jdbc type
89 */
90 public static boolean isJdbcType(Class c)
91 {
92 return CLASS_TO_TYPE_MAP.containsKey(c);
93 }
94
95 /**
96 * Constructor
97 */
98 private TypeMapper()
99 {
100 }
101 }
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.text;
21
22 import java.util.HashMap;
23 import java.util.Map;
24 /**
25 * A simple implementation of generator
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 */
28 public class SimpleTextGenerator implements TextGenerator
29 {
30
31 /** the delimiter **/
32 private String _delimiter;
33
34 /** sub delimiter **/
35 private String _subDelimiter;
36
37 /** attr generators * */
38 private Map _generators = new HashMap();
39
40 /**
41 * Constructor
42 */
43 public SimpleTextGenerator(String delimiter, String subDelimiter)
44 {
45 _delimiter = delimiter;
46 _subDelimiter = subDelimiter;
47 }
48
49 /**
50 * add text generator to the sub specification
51 * @param subSpec the sub spec
52 * @param gen the sub generator
53 */
54 public void addGenerator(String subSpec, TextGenerator gen)
55 {
56 _generators.put(subSpec, gen);
57 }
58
59 /**
60 * {@inheritDoc}
61 */
62 public StringBuffer generateText(String spec, Object obj)
63 {
64 StringBuffer sb = new StringBuffer();
65 generateText(spec, obj, sb);
66 return sb;
67 }
68
69 /**
70 * {@inheritDoc}
71 */
72 public void generateText(String spec, Object obj, StringBuffer sb)
73 {
74 String[] fields = spec.split(_delimiter);
75 for (int i = 0; i < fields.length; i++)
76 {
77 if (_subDelimiter != null)
78 {
79 TextGenerator gen = getGenerator(fields[i]);
80 if (gen == null)
81 {
82 throw new IllegalArgumentException("No sub generator for " + fields[i]);
83 } else
84 {
85 gen.generateText(null, obj, sb);
86 }
87 } else
88 {
89 String specs[] = fields[i].split(_subDelimiter);
90 TextGenerator subGen = getGenerator(specs[0]);
91 if (subGen == null)
92 {
93 throw new IllegalArgumentException("No sub generator for " + specs[0]);
94 }
95 if (specs.length > 1)
96 {
97 subGen.generateText(specs[1], obj, sb);
98 } else
99 {
100 subGen.generateText(null, obj, sb);
101 }
102 }
103 }
104 }
105
106 /**
107 * Get the generator for subSpec
108 * @param subSpec the sub spec
109 * @return the generator for the sub spec
110 */
111 public TextGenerator getGenerator(String subSpec)
112 {
113 return (TextGenerator) _generators.get(subSpec);
114 }
115 }
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.text;
21
22 /**
23 * A simple interface for text generation.
24 * The generator generates some text on a passed in regarding a target object.
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 */
27 public interface TextGenerator
28 {
29 /**
30 * Generate some text through the spec passed in
31 * @param spec the specification
32 * @param obj the target object where the text should be generate towards
33 * @return the text
34 */
35 public void generateText(String spec, Object obj, StringBuffer sb);
36 }
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.util;
21
22 import java.io.IOException;
23 import java.io.Writer;
24 import java.util.*;
25 import java.util.HashMap;
26 import java.util.Map;
27 import org.onemind.commons.java.lang.MutableLong;
28 /**
29 * For counting things
30 * @author TiongHiang Lee (thlee@onemindsoft.org)
31 * @version $Id: Counter.java,v 1.2 2005/06/22 22:58:25 thlee Exp $ $Name: $
32 */
33 public class Counter
34 {
35
36 /** the counts **/
37 private final Map counts = new HashMap();
38
39 /**
40 * Constructor
41 */
42 public Counter()
43 {
44 }
45
46 /**
47 * Add count. Count as 1 if it is not counted before
48 * @param counted
49 */
50 public void count(Object counted)
51 {
52 count(counted, 1);
53 }
54
55 /**
56 * Adjust count by value
57 * @param counted the counted
58 * @param countValue the count value
59 */
60 public void count(Object counted, long countValue)
61 {
62 MutableLong count = (MutableLong) counts.get(counted);
63 if (count == null)
64 {
65 counts.put(counted, new MutableLong(countValue));
66 } else
67 {
68 count.inc(countValue);
69 }
70 }
71
72 /**
73 * Remove the count. Count as -1 if it is not counted before
74 * @param counted the counted
75 */
76 public void removeCount(Object counted)
77 {
78 MutableLong count = (MutableLong) counts.get(counted);
79 if (count == null)
80 {
81 counts.put(counted, new MutableLong(-1));
82 } else
83 {
84 count.dec(1);
85 }
86 }
87
88 /**
89 * Get the count
90 * @param counted the counted
91 * @return the count
92 */
93 public long getCount(Object counted)
94 {
95 MutableLong count = (MutableLong) counts.get(counted);
96 if (count == null)
97 {
98 return 0;
99 } else
100 {
101 return count.longValue();
102 }
103 }
104
105 /**
106 * Dump to output
107 * @param writer the writer
108 */
109 public void dump(Writer writer) throws IOException
110 {
111 MapUtils.dump(counts, writer);
112 }
113
114 /**
115 * Reset the count for counted
116 * @param counted the counted
117 */
118 public void resetCount(Object counted)
119 {
120 counts.remove(counted);
121 }
122
123 /**
124 * Reset all the counters
125 */
126 public void resetAll()
127 {
128 counts.clear();
129 }
130
131 public String toString()
132 {
133 StringBuffer sb = new StringBuffer(super.toString());
134 sb.append(" - [");
135 Iterator it = counts.keySet().iterator();
136 while (it.hasNext())
137 {
138 Object obj = it.next();
139 sb.append(obj);
140 sb.append("=");
141 sb.append(counts.get(obj));
142 if (it.hasNext())
143 {
144 sb.append(", ");
145 }
146 }
147 sb.append("]");
148 return sb.toString();
149 }
150 }
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.util;
21
22 import java.io.*;
23 /**
24 * File related utilities methods
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: FileUtils.java,v 1.3 2004/09/19 20:07:04 thlee Exp $ $Name: $
27 */
28 public final class FileUtils
29 {
30
31 /**
32 * {@inheritDoc}
33 */
34 private FileUtils()
35 {
36 };
37
38 /** the forward slash * */
39 private static final String FSLASH = "/";
40
41 /** the back slash * */
42 private static final String BSLASH = "\\";
43
44 /** the separator * */
45 private static final String SEPARATOR = FSLASH; //use forward slash since
46
47 // both unix and windows jdk
48 // support it
49 /**
50 * Concat the strings to be a valid file path
51 * @param args the string
52 * @return the file path
53 * @todo add doc to describe the behavior
54 */
55 public static String concatFilePath(String[] args)
56 {
57 StringBuffer sb = new StringBuffer(args[0]);
58 for (int i = 1; i < args.length; i++)
59 {
60 concatFilePath(sb, args[i]);
61 }
62 return sb.toString();
63 }
64
65 //TODO: Describe behaviors
66 /**
67 * Concat filepath with the prefix and suffix
68 * @param prefix the prefix
69 * @param suffix the suffix
70 * @return the file path
71 * @todo add doc to describe the behavior
72 */
73 public static String concatFilePath(String prefix, String suffix)
74 {
75 return concatFilePath(new StringBuffer(prefix), suffix);
76 }
77
78 /**
79 * concat a meaning file path
80 * @param prefix the prefix
81 * @param suffix the suffix
82 * @return the concat'ed file path
83 */
84 private static String concatFilePath(StringBuffer prefix, String suffix)
85 {
86 String pf = prefix.toString();
87 if (pf.endsWith(FSLASH) || pf.endsWith(BSLASH))
88 {
89 if (suffix.startsWith(FSLASH) || suffix.startsWith(BSLASH))
90 {
91 if (suffix.length() > 1)
92 {
93 prefix.append(suffix.substring(1));
94 }
95 //else do nothing
96 } else
97 {
98 prefix.append(suffix);
99 }
100 } else
101 {
102 if (suffix.startsWith(FSLASH) || suffix.startsWith(BSLASH))
103 {
104 prefix.append(suffix);
105 } else
106 {
107 prefix.append(FSLASH);
108 prefix.append(suffix);
109 }
110 }
111 return prefix.toString();
112 }
113
114 /**
115 * Copy the input to the output. Will not close the output after copying
116 * @param input the input stream
117 * @param output the output
118 * @param chunkSize the chunk size
119 *
120 */
121 public static void copyStream(InputStream input, OutputStream output, int chunkSize) throws IOException
122 {
123 byte[] buffer = new byte[chunkSize];
124 int n = input.read(buffer, 0, chunkSize);
125 while (n != -1)
126 {
127 output.write(buffer, 0, n);
128 n = input.read(buffer, 0, chunkSize);
129 }
130 output.flush();
131 }
132 }
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.util;
21
22 import java.io.*;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.util.logging.LogManager;
26 /**
27 * Utility methods for loggin
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: LogUtils.java,v 1.4 2005/08/08 05:21:51 thlee Exp $ $Name: $
30 */
31 public final class LogUtils
32 {
33
34 /**
35 * {@inheritDoc}
36 */
37 private LogUtils()
38 {
39 }
40
41 /**
42 * Init java logging by looking for logging.properties in the class paths
43 */
44 public static void initLoggingFromClassPath()
45 {
46 String classPath = (String) System.getProperties().get("java.class.path");
47 String[] paths = null;
48 if (classPath.indexOf(";") != -1)
49 { //must be windows
50 paths = classPath.split(";");
51 } else
52 {
53 paths = classPath.split(":");
54 }
55 for (int i = 0; i < paths.length; i++)
56 {
57 if (!paths[i].endsWith(".jar"))
58 {
59 String config = FileUtils.concatFilePath(paths[i], "logging.properties");
60 if (new File(config).exists())
61 {
62 //System.out.println("Use logging configuration " + config);
63 try
64 {
65 LogManager.getLogManager().readConfiguration(new FileInputStream(config));
66 } catch (Exception e)
67 {
68 //nothing it can do
69 //System.out.println("- init logging problem: " + e.getMessage());
70 }
71 }
72 }
73 }
74 }
75
76 /**
77 * Get the stack trace in a string
78 * @param e the exception
79 * @return the stack trace string
80 */
81 public static String getTrace(Throwable e)
82 {
83 ByteArrayOutputStream buffer = new ByteArrayOutputStream();
84 PrintStream ps = new PrintStream(buffer);
85 e.printStackTrace(ps);
86 ps.flush();
87 return new String(buffer.toByteArray());
88 }
89 }
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.util;
21
22 import java.io.*;
23 import java.io.IOException;
24 import java.io.Writer;
25 import java.util.Iterator;
26 import java.util.Map;
27 /**
28 * A map utility class
29 * @author TiongHiang Lee (thlee@onemindsoft.org)
30 * @version $Id: MapUtils.java,v 1.3 2004/10/31 16:02:21 thlee Exp $ $Name: $
31 */
32 public final class MapUtils
33 {
34
35 /**
36 * {@inheritDoc}
37 */
38 private MapUtils()
39 {
40 };
41
42 /**
43 * Dump the map in name=value lines
44 * @param m the map
45 * @param writer the writer
46 * @throws IOException if there's IO problem
47 */
48 public static void dump(Map m, Writer writer) throws IOException
49 {
50 Iterator it = m.keySet().iterator();
51 while (it.hasNext())
52 {
53 String key = (String) it.next();
54 writer.write(key + " = " + m.get(key) + "\n");
55 }
56 }
57
58 /**
59 * Get a string representation of the content in the map
60 * @param m the map
61 * @return a string with the format of a=b separated by line break
62 * @throws IOException
63 */
64 public static String toString(Map m) throws IOException
65 {
66 ByteArrayOutputStream bout = new ByteArrayOutputStream();
67 Writer writer = new OutputStreamWriter(bout);
68 dump(m, writer);
69 writer.flush();
70 bout.close();
71 return new String(bout.toByteArray());
72 }
73 }
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 package org.onemind.commons.java.util;
20
21 /**
22 * Property utilities
23 * @author TiongHiang Lee (thlee@onemindsoft.org)
24 * @version $Id: ObjectUtils.java,v 1.2 2004/08/26 12:33:17 thlee Exp $ $Name: $
25 */
26 public final class ObjectUtils
27 {
28
29 /**
30 * Constructor
31 */
32 private ObjectUtils()
33 {
34 super();
35 }
36
37 /**
38 * Convert the object the boolean, return the default if it cannot be converted
39 * @param value the value
40 * @param def the default
41 * @return the converted value, or def if value is null
42 */
43 public static final boolean toBool(Object value, boolean def)
44 {
45 if (value instanceof Boolean)
46 {
47 return ((Boolean) value).booleanValue();
48 } else if (value instanceof String)
49 {
50 if ("TRUE".equalsIgnoreCase((String) value))
51 {
52 return true;
53 } else if ("FALSE".equalsIgnoreCase((String) value))
54 {
55 return false;
56 } else
57 {
58 return def;
59 }
60 } else
61 {
62 return def;
63 }
64 }
65
66 /**
67 * Convert the object to int, or return the default if it cannot be converted
68 * @param value the value
69 * @param def the default
70 * @return the converted int, or default if it cannot be converted
71 */
72 public static int toInt(Object value, int def)
73 {
74 if (value instanceof Integer)
75 {
76 return ((Integer) value).intValue();
77 } else if (value instanceof String)
78 {
79 try
80 {
81 return Integer.parseInt((String) value);
82 } catch (NumberFormatException e)
83 {
84 return def;
85 }
86 } else
87 {
88 return def;
89 }
90 }
91
92 /**
93 * Convert the object to long, or return the default if it cannot be converted
94 * @param value the value
95 * @param def the default
96 * @return the converted int, or default if it cannot be converted
97 */
98 public static long toLong(Object value, long def)
99 {
100 if (value instanceof Long)
101 {
102 return ((Long) value).longValue();
103 } else if (value instanceof String)
104 {
105 try
106 {
107 return Long.parseLong((String) value);
108 } catch (NumberFormatException e)
109 {
110 return def;
111 }
112 } else
113 {
114 return def;
115 }
116 }
117
118 /**
119 * Convert the object to float, or return the default if it cannot be converted
120 * @param value the value
121 * @param def the default
122 * @return the converted int, or default if it cannot be converted
123 */
124 public static float toFloat(Object value, float def)
125 {
126 if (value instanceof Float)
127 {
128 return ((Float) value).floatValue();
129 } else if (value instanceof String)
130 {
131 try
132 {
133 return Float.parseFloat((String) value);
134 } catch (NumberFormatException e)
135 {
136 return def;
137 }
138 } else
139 {
140 return def;
141 }
142 }
143
144 /**
145 * Convert the object to double, or return the default if it cannot be converted
146 * @param value the value
147 * @param def the default
148 * @return the converted int, or default if it cannot be converted
149 */
150 public static double toDouble(Object value, double def)
151 {
152 if (value instanceof Double)
153 {
154 return ((Double) value).doubleValue();
155 } else if (value instanceof String)
156 {
157 try
158 {
159 return Double.parseDouble((String) value);
160 } catch (NumberFormatException e)
161 {
162 return def;
163 }
164 } else
165 {
166 return def;
167 }
168 }
169 }
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.util;
21
22 import java.io.File;
23 import java.util.*;
24 import java.util.Enumeration;
25 import java.util.HashMap;
26 import java.util.Map;
27 import javax.servlet.ServletConfig;
28 import javax.servlet.http.HttpServletRequest;
29 import javax.servlet.http.HttpSession;
30 import org.apache.commons.fileupload.*;
31 import org.apache.commons.fileupload.DiskFileUpload;
32 import org.apache.commons.fileupload.FileUpload;
33 /**
34 * The servlet utiltity
35 * @author TiongHiang Lee (thlee@onemindsoft.org)
36 * @version $Id: ServletUtils.java,v 1.3 2004/10/23 15:27:01 thlee Exp $ $Name: $
37 */
38 public final class ServletUtils
39 {
40
41 /**
42 * Constructor
43 */
44 private ServletUtils()
45 {
46 };
47
48 /**
49 * Get the request environment
50 * @param req the request
51 * @return the environment in a map
52 */
53 public static Map getRequestEnvironment(HttpServletRequest req)
54 {
55 Map m = new HashMap();
56 m.put("REQUEST", req);
57 m.put("REQUEST_AUTH_TYPE", req.getAuthType());
58 //m.put("REQUEST_CONTEXT_PATH", req.getContextPath());
59 m.put("REQUEST_COOKIES", req.getCookies());
60 Enumeration enum = req.getHeaderNames();
61 while (enum.hasMoreElements())
62 {
63 String header = (String) enum.nextElement();
64 String value = req.getHeader(header);
65 m.put(header, value);
66 }
67 m.put("REQUEST_METHOD", req.getMethod());
68 m.put("PATH_INFO", req.getPathInfo());
69 m.put("PATH_TRANSLATED", req.getPathTranslated());
70 m.put("QUERY_STRING", req.getQueryString());
71 m.put("REMOTE_ADDR", req.getRemoteAddr());
72 m.put("REMOTE_HOST", req.getRemoteHost());
73 m.put("REMOTE_USER", req.getRemoteUser());
74 m.put("REQUESTED_SESSION_ID", req.getRequestedSessionId());
75 m.put("REQUEST_URI", req.getRequestURI());
76 //m.put("REQUEST_URL", req.getRequestURL());
77 m.put("SERVLET_PATH", req.getServletPath());
78 m.put("SESSION", req.getSession(true));
79 //env
80 return m;
81 }
82
83 /**
84 * Get request attributes (Only for jsdk 2.3)
85 * @param req the request
86 * @return the servlet attributes
87 */
88 public static Map getExtraRequestEnvironment(HttpServletRequest req)
89 {
90 Map m = new HashMap();
91 Enumeration enum = req.getAttributeNames();
92 while (enum.hasMoreElements())
93 {
94 String attr = (String) enum.nextElement();
95 m.put(attr, req.getAttribute(attr));
96 }
97 m.put("CHARACTER_ENCODING", req.getCharacterEncoding());
98 m.put("CONTENT_LENGTH", new Integer(req.getContentLength()));
99 m.put("CONTENT_TYPE", req.getContentType());
100 m.put("REQUEST_PROTOCOL", req.getProtocol());
101 m.put("REQUEST_SCHEME", req.getScheme());
102 m.put("SERVER_NAME", req.getServerName());
103 m.put("SERVER_PORT", new Integer(req.getServerPort()));
104 return m;
105 }
106
107 /**
108 * Get the servlet environment from the config
109 * @param config the config
110 * @return the environment in a map
111 */
112 public static Map getServletEnvironment(ServletConfig config)
113 {
114 Map m = new HashMap();
115 m.put("SERVLET_CONTEXT", config.getServletContext());
116 return m;
117 }
118
119 /**
120 * Get the request parameters in a mp
121 * @param req the request
122 * @return the environment in the map
123 */
124 public static Map getRequestParameters(HttpServletRequest req, DiskFileUpload upload) throws FileUploadException
125 {
126 Map m = new HashMap();
127 if (FileUpload.isMultipartContent(req))
128 {
129 // Parse the request
130 List items = upload.parseRequest(req);
131 Iterator iter = items.iterator();
132 while (iter.hasNext())
133 {
134 FileItem item = (FileItem) iter.next();
135 if (item.isFormField())
136 {
137 m.put(item.getFieldName(), item.getString());
138 } else
139 {
140 String fieldName = item.getFieldName();
141 m.put(fieldName + ".FILENAME", item.getName()); //file name
142 m.put(fieldName + ".CONTENT_TYPE", item.getContentType());
143 m.put(fieldName + ".ITEM", item);
144 }
145 }
146 } else
147 {
148 Enumeration enum = req.getParameterNames();
149 while (enum.hasMoreElements())
150 {
151 String key = (String) enum.nextElement();
152 String[] value = req.getParameterValues(key);
153 if (value.length == 0)
154 {
155 m.put(key, null);
156 } else if (value.length == 1)
157 {
158 m.put(key, value[0]);
159 } else
160 {
161 m.put(key, value);
162 }
163 }
164 }
165 return m;
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.util;
21
22 import java.util.Collection;
23 /**
24 * String utilities method
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: StringUtils.java,v 1.3 2004/09/19 20:07:32 thlee Exp $ $Name: $
27 */
28 public final class StringUtils
29 {
30
31 /**
32 * Constructor
33 */
34 private StringUtils()
35 {
36 super();
37 }
38
39 /**
40 * Concat the collection l to string with delimenter
41 * @param l the collection
42 * @param delimiter the delimiter
43 * @return the result string
44 */
45 public static String concat(Collection l, String delimiter)
46 {
47 return concat(l.toArray(), delimiter);
48 }
49
50 /**
51 * Concant the object in the array (using objects.toString()), delimited by delimiter
52 * @param objects the objects
53 * @param delimiter the delimiter
54 * @return a string
55 */
56 public static String concat(Object[] objects, String delimiter)
57 {
58 StringBuffer sb = new StringBuffer();
59 for (int i = 0; i < objects.length; i++)
60 {
61 sb.append(objects[i]);
62 if (i < (objects.length - 1))
63 {
64 sb.append(delimiter);
65 }
66 }
67 return sb.toString();
68 }
69
70 /**
71 * Return the substring after the first occurrance of pattern
72 * @param str the str
73 * @param pattern the pattern
74 * @return the substring of pattern can be matched in str, or null
75 */
76 public static String substringAfter(String str, String pattern)
77 {
78 int i = str.indexOf(pattern);
79 if (i == -1)
80 {
81 return null;
82 }
83 return str.substring(i + pattern.length());
84 }
85
86 /**
87 * Return substring of str after the the last occurrance of pattern
88 * @param str the str
89 * @param pattern the pattern
90 * @return the substring if pattern can be matched in the str, or null
91 */
92 public static String substringAfterLast(String str, String pattern)
93 {
94 int i = str.lastIndexOf(pattern);
95 if (i == -1)
96 {
97 return null;
98 }
99 return str.substring(i + pattern.length());
100 }
101
102 /**
103 * Return substring of str before the last occurrance of str
104 * @param str the str
105 * @param pattern the pattern
106 * @return the substring if pattern can be matched, or null
107 */
108 public static String substringBeforeLast(String str, String pattern)
109 {
110 int i = str.lastIndexOf(pattern);
111 if (i == -1)
112 {
113 return null;
114 }
115 return str.substring(0, i);
116 }
117
118 /**
119 * Whether the string is empty
120 * @param str whether is null or zero length (after trim)
121 * @return true if null of zero length after trim
122 */
123 public static boolean isNullOrEmpty(String str)
124 {
125 return (str == null || str.trim().length() == 0);
126 }
127
128 /**
129 * Whether the string is empty
130 * @param str whether is null or zero length (after trim)
131 * @return true if null of zero length after trim
132 */
133 public static boolean isNullOrEmpty(Object strObject)
134 {
135 if (strObject == null)
136 {
137 return true;
138 } else if (strObject instanceof String)
139 {
140 return isNullOrEmpty((String) strObject);
141 } else
142 {
143 return isNullOrEmpty(strObject.toString());
144 }
145 }
146 }
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.xml.digest;
21
22 import java.util.EventObject;
23 import org.onemind.commons.java.event.*;
24 import org.onemind.commons.java.event.EventFirer;
25 import org.onemind.commons.java.event.EventListenerList;
26 import org.xml.sax.Attributes;
27 import org.xml.sax.SAXException;
28 /**
29 * The abstract implementation of ElementCreatorDigester. The element creator will fire an event
30 * at the end of digestion
31 * @author TiongHiang Lee (thlee@onemindsoft.org)
32 */
33 public abstract class AbstractElementCreatorDigester extends DefaultDigester implements ElementCreatorDigester
34 {
35 /** the listener list **/
36 private final EventListenerList _listeners = new EventListenerList();
37
38 /** the created object **/
39 private Object _created;
40
41 /** event firer for element event **/
42 private static final EventFirer _FIRER = new EventFirer()
43 {
44
45 /**
46 * {@inheritDoc}
47 */
48 public void fireEvent(EventListener listener, EventObject evt)
49 {
50 ((ElementListener) listener).objectCreated(((ElementEvent) evt).getElement());
51 }
52 };
53
54 /**
55 * Constructor
56 * @param name the element name
57 */
58 public AbstractElementCreatorDigester(String name)
59 {
60 super(name);
61 }
62
63 /**
64 * {@inheritDoc}
65 */
66 public final void addListener(ElementListener l)
67 {
68 _listeners.addListener(l);
69 }
70
71 /**
72 * {@inheritDoc}
73 */
74 public final void removeListener(ElementListener l)
75 {
76 _listeners.removeListener(l);
77 }
78
79 /**
80 * {@inheritDoc}
81 */
82 public void endDigest(SaxDigesterHandler handler) throws SAXException
83 {
84 _listeners.fireEvent(_FIRER, new ElementEvent(this, getCreatedElement()));
85 }
86
87 /**
88 * Set the created element
89 * @param obj the object
90 */
91 protected final void setCreatedElement(Object obj)
92 {
93 _created = obj;
94 }
95
96 /**
97 * {@inheritDoc}
98 */
99 public final Object getCreatedElement()
100 {
101 return _created;
102 }
103 }
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.xml.digest;
21
22 import org.onemind.commons.java.lang.reflect.ReflectUtils;
23 import org.onemind.commons.java.util.StringUtils;
24 import org.xml.sax.Attributes;
25 import org.xml.sax.SAXException;
26 /**
27 * A ChainedDigester is a helper digester that chains the digestion
28 * of xml dynamically based on a dynamic digester configured as a
29 * attribute name.
30 * @author TiongHiang Lee (thlee@onemindsoft.org)
31 */
32 public class ChainedDigester extends AbstractElementCreatorDigester
33 {
34 /** the attribute name that specify the digester class **/
35 private String _attrName;
36
37 /** the argument to pass the constructor of the dynamic digester **/
38 private Object[] _args;
39
40 /**
41 * Constructor
42 * @param name the name of element
43 */
44 public ChainedDigester(String name)
45 {
46 this(name, "className", null);
47 }
48
49 /**
50 * Constructor
51 * @param name the element name
52 * @param attrName the attr
53 */
54 public ChainedDigester(String name, String attrName)
55 {
56 this(name, attrName, null);
57 }
58
59 /**
60 * Constructor
61 * @param name the element name
62 * @param attrName the attribute the specifies the dynamic digester
63 * @param args arguments to pass to constructor of the dynamic digester
64 */
65 public ChainedDigester(String name, String attrName, Object[] args)
66 {
67 super(name);
68 _attrName = attrName;
69 _args = args;
70 }
71
72 /**
73 * {@inheritDoc}
74 */
75 public void startDigest(SaxDigesterHandler handler, Attributes attrs) throws SAXException
76 {
77 String className = attrs.getValue(_attrName);
78 if (StringUtils.isNullOrEmpty(className))
79 {
80 throw new SAXException("className attribute need to be present at " + handler.getCurrentPath());
81 } else
82 {
83 try
84 {
85 ElementDigester dig = (ElementDigester) ReflectUtils.newInstance(ReflectUtils.getClass(className), _args);
86 setCreatedElement(dig);
87 handler.addSubDigester(dig);
88 } catch (Exception e)
89 {
90 throw new SAXException("Cannot instantiate render context " + className, e);
91 }
92 }
93 }
94 }
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@thinklient.org
18 */
19
20 package org.onemind.commons.java.xml.digest;
21
22 import org.xml.sax.Attributes;
23 import org.xml.sax.SAXException;
24 /**
25 * A default digesters that does nothing
26 * @author TiongHiang Lee (thlee@thinklient.org)
27 */
28 public class DefaultDigester implements ElementDigester
29 {
30
31 /** the element name **/
32 private final String _elementName;
33
34 /**
35 * Constructor
36 * @param name the name
37 */
38 public DefaultDigester(String name)
39 {
40 _elementName = name;
41 }
42
43 /**
44 * {@inheritDoc}
45 */
46 public void startDigest(SaxDigesterHandler handler, Attributes attrs) throws SAXException
47 {
48 //do nothing
49 }
50
51 /**
52 * {@inheritDoc}
53 */
54 public void endDigest(SaxDigesterHandler handler) throws SAXException
55 {
56 //do nothing
57 }
58
59 /**
60 * {@inheritDoc}
61 */
62 public void characters(SaxDigesterHandler handler, char[] chars, int offset, int length) throws SAXException
63 {
64 // do nothing
65 }
66
67 /**
68 * {@inheritDoc}
69 */
70 public final String getElementName()
71 {
72 return _elementName;
73 }
74 }
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.xml.digest;
21
22 /**
23 * An creator digester is a digester that digests an element in xml and
24 * creates an element object as represented by xml. It provides a mechanism
25 * for xml element digestion implementation outside of the element object itself.
26 *
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: ElementCreatorDigester.java,v 1.1 2005/01/30 06:30:53 thlee Exp $ $Name: $
29 */
30 public interface ElementCreatorDigester extends ElementDigester
31 {
32
33 /**
34 * Add listener
35 * @param l the listener
36 */
37 public abstract void addListener(ElementListener l);
38
39 /**
40 * Remove listener
41 * @param l the listener
42 */
43 public abstract void removeListener(ElementListener l);
44
45 /**
46 * Get the created object
47 * @return the created object
48 */
49 public abstract Object getCreatedElement();
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@thinklient.org
18 */
19
20 package org.onemind.commons.java.xml.digest;
21
22 import org.xml.sax.Attributes;
23 import org.xml.sax.SAXException;
24 /**
25 * An element digester digest a particular element inside an xml file in common-digest framework
26 * @author TiongHiang Lee (thlee@thinklient.org)
27 * @version $Id: ElementDigester.java,v 1.3 2005/06/22 22:58:58 thlee Exp $ $Name: $
28 */
29 public interface ElementDigester
30 {
31 /**
32 * Get the element name
33 * @return the element name
34 */
35 public String getElementName();
36
37 /**
38 * Start an element with the given attributes
39 * @param handler the handler
40 * @param attr the attributes
41 * @throws SAXException if there's handling exception
42 */
43 public void startDigest(SaxDigesterHandler handler, Attributes attr) throws SAXException;
44
45 /**
46 * End the element
47 * @param handler the handler
48 * @throws SAXException if there's handling exception
49 */
50 public void endDigest(SaxDigesterHandler handler) throws SAXException;
51
52 /**
53 * Handle the characters
54 * @param handler the handler
55 * @param chars the characters
56 * @param offset the offset
57 * @param length the length
58 * @throws SAXException if there's parse problem
59 */
60 public void characters(SaxDigesterHandler handler, char[] chars, int offset, int length) throws SAXException;
61 }
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.xml.digest;
21
22 import java.util.EventObject;
23 /**
24 * The element event
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: ElementEvent.java,v 1.1 2005/01/30 06:30:53 thlee Exp $ $Name: $
27 */
28 public class ElementEvent extends EventObject
29 {
30
31 /** the element **/
32 private Object _element;
33
34 /**
35 * Constructor
36 * @param dig the digester the fires the event
37 * @param element the element created
38 */
39 public ElementEvent(ElementDigester dig, Object element)
40 {
41 super(dig);
42 _element = element;
43 }
44
45 /**
46 * the element
47 * @return the element
48 */
49 public Object getElement()
50 {
51 return _element;
52 }
53 }
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.xml.digest;
21
22 import org.onemind.commons.java.event.EventListener;
23
24 /**
25 * The object creation listener
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: ElementListener.java,v 1.1 2005/01/30 06:30:53 thlee Exp $ $Name: $
28 */
29 public interface ElementListener extends EventListener
30 {
31 /**
32 * Called by an ElementCreatorDigester when an element is created
33 * @param obj the object created
34 */
35 public void objectCreated(Object obj);
36 }
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@thinklient.org
18 */
19
20 package org.onemind.commons.java.xml.digest;
21
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.*;
25 import java.util.logging.Level;
26 import java.util.logging.Logger;
27 import javax.xml.parsers.*;
28 import org.xml.sax.Attributes;
29 import org.xml.sax.SAXException;
30 import org.xml.sax.helpers.DefaultHandler;
31 /**
32 * The SaxDigesterHandler use digesters to digest the elements in the xml. The digesters can be added using the addDigester(). By
33 * default the sequential digester list is used.
34 * @author TiongHiang Lee (thlee@thinklient.org)
35 * @version $Id: SaxDigesterHandler.java,v 1.3 2005/01/30 06:31:37 thlee Exp $ $Name: $
36 */
37 public class SaxDigesterHandler extends DefaultHandler
38 {
39
40 /** the logger * */
41 private static final Logger _logger = Logger.getLogger(SaxDigesterHandler.class.getName());
42
43 /** the map contains subdigesters **/
44 private Map _digesters = new HashMap();
45
46 /** keep track of the path for current element **/
47 private List _elementPath = new ArrayList();
48
49 /**
50 * Constructor
51 */
52 public SaxDigesterHandler()
53 {
54 }
55
56 /**
57 * Adding a digester to the root path
58 * @param dig the digester
59 */
60 public void addDigester(ElementDigester dig)
61 {
62 addDigester(null, dig);
63 }
64
65 /**
66 * Add a digester for the path
67 * @param path the path
68 * @param dig the digester
69 */
70 public void addDigester(String path, ElementDigester dig)
71 {
72 if (path == null)
73 {
74 _digesters.put(dig.getElementName(), dig);
75 } else
76 {
77 _digesters.put(path + "/" + dig.getElementName(), dig);
78 }
79 }
80
81 /**
82 * Add a subdigester to current element path
83 * @param dig the digester
84 */
85 public void addSubDigester(ElementDigester dig)
86 {
87 String path = getCurrentPath();
88 addDigester(path, dig);
89 }
90
91 /**
92 * Add a sub digester at a path of current path + prefixPath
93 * @param prefixPath the prefix path
94 * @param dig the digester
95 */
96 public void addSubDigester(String prefixPath, ElementDigester dig)
97 {
98 String path = getCurrentPath();
99 if (path == null)
100 {
101 addDigester(prefixPath, dig);
102 } else if (prefixPath == null)
103 {
104 addDigester(path, dig);
105 } else
106 {
107 addDigester(path + "/" + prefixPath, dig);
108 }
109 }
110
111 /**
112 * Append the name to the element path and return the new path string
113 * @param name the name of new element
114 * @return the new path string
115 */
116 private String appendElementPath(String name)
117 {
118 int i = _elementPath.size();
119 if (i > 0)
120 {
121 String str = (String) _elementPath.get(i - 1);
122 String newStr = str + "/" + name;
123 _elementPath.add(newStr);
124 return newStr;
125 } else
126 {
127 _elementPath.add(name);
128 return name;
129 }
130 }
131
132 /**
133 * {@inheritDoc}
134 */
135 public void characters(char[] ch, int start, int length) throws SAXException
136 {
137 ElementDigester dig = getDigester(getCurrentPath());
138 if (dig != null)
139 {
140 dig.characters(this, ch, start, length);
141 }
142 }
143
144 /**
145 * {@inheritDoc}
146 */
147 public void endDocument() throws SAXException
148 {
149 //do nothing
150 }
151
152 /**
153 * {@inheritDoc}
154 */
155 public void endElement(String uri, String localName, String qName) throws SAXException
156 {
157 String str = removeElementPath(qName);
158 ElementDigester dig = (ElementDigester) getDigester(str);
159 if (dig != null)
160 {
161 dig.endDigest(this);
162 }
163 }
164
165 /**
166 * Get the current element path
167 * @return the path, or null if at start of document
168 */
169 public String getCurrentPath()
170 {
171 int i = _elementPath.size();
172 if (i > 0)
173 {
174 return (String) _elementPath.get(i - 1);
175 } else
176 {
177 return null;
178 }
179 }
180
181 /**
182 * Get the digester for particular path
183 * @param path the path
184 * @return the digester, or null if there's none found
185 */
186 private ElementDigester getDigester(String path)
187 {
188 return (ElementDigester) _digesters.get(path);
189 }
190
191 /**
192 * Remove the element path
193 * @param qname the element name is being removed
194 * @return the path string before the path is removed
195 */
196 private String removeElementPath(String qname)
197 {
198 int i = _elementPath.size();
199 if (i > 0)
200 {
201 String str = (String) _elementPath.remove(i - 1);
202 return str;
203 } else
204 {
205 throw new IllegalStateException("Cannot remove element path " + qname);
206 }
207 }
208
209 /**
210 * {@inheritDoc}
211 */
212 public void startDocument() throws SAXException
213 {
214 //do nothing
215 }
216
217 /**
218 * Call start of particular element digester, if there's any
219 * @param attr the attribute
220 * @param path the path
221 * @throws SAXException
222 */
223 private void startDigest(String path, Attributes attr) throws SAXException
224 {
225 if (_logger.isLoggable(Level.FINEST))
226 {
227 _logger.finest("Digesting " + path);
228 }
229 ElementDigester dig = (ElementDigester) getDigester(path);
230 if (dig != null)
231 {
232 if (_logger.isLoggable(Level.FINEST))
233 {
234 _logger.finest("with " + dig);
235 }
236 dig.startDigest(this, attr);
237 }
238 }
239
240 /**
241 * {@inheritDoc}
242 */
243 public void startElement(String namespaceURI, String lName, // local name
244 String qName, // qualified name
245 Attributes attrs) throws SAXException
246 {
247 String newPath = appendElementPath(qName);
248 startDigest(newPath, attrs);
249 }
250
251 /**
252 * Parse an input
253 * @param stream the stream
254 * @throws ParserConfigurationException
255 * @throws SAXException
256 * @throws IOException
257 */
258 public synchronized void parse(InputStream stream) throws ParserConfigurationException, SAXException, IOException
259 {
260 SAXParserFactory fac = SAXParserFactory.newInstance();
261 SAXParser parser = fac.newSAXParser();
262 parser.parse(stream, this);
263 }
264 }
0
1 /*
2 * Copyright (C) 2004 TiongHiang Lee
3 *
4 * This library is free software; you can redistribute it and/or
5 * modify it under the terms of the GNU Lesser General Public
6 * License as published by the Free Software Foundation; either
7 * version 2.1 of the License, or (at your option) any later version.
8 *
9 * 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 public class Dummy
21 {
22 }
0 <?xml version="1.0" encoding="UTF-8" ?>
1 <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
2
3 <log4j:configuration xmlns:log4j='http://jakarta.apache.org/log4j/'>
4 <appender name="Console" class="org.apache.log4j.ConsoleAppender">
5 <layout class="org.apache.log4j.PatternLayout">
6 <param name="ConversionPattern" value="%d %-5p %C{1} - %m%n"/>
7 </layout>
8 </appender>
9
10 <appender name="NullAppender" class="org.apache.log4j.varia.NullAppender"/>
11
12 <category name="org.onemind.commons.java.lang.reflect">
13 <priority value="warn" />
14 <appender-ref ref="Console"/>
15 </category>
16
17 <category name="org.onemind.commons.java.util">
18 <priority value="warn" />
19 <appender-ref ref="Console"/>
20 </category>
21
22 <root>
23 <priority value ="fatal" />
24 <appender-ref ref="NullAppender" />
25 </root>
26 </log4j:configuration>
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 junit.framework.TestCase;
23 /**
24 * Unit test for BiMap
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: BiMapTest.java,v 1.1 2004/09/29 02:45:36 thlee Exp $ $Name: $
27 */
28 public class BiMapTest extends TestCase
29 {
30
31 /**
32 * Test bimap functionality
33 * @throws Exception
34 */
35 public void testBiMap() throws Exception
36 {
37 BiMap biMap = new BiMap();
38 biMap.put("1", "one");
39 //assert values is correct
40 BiMap inverse = biMap.getInverse();
41 assertEquals("one", biMap.get("1"));
42 assertEquals("1", inverse.get("one"));
43 try
44 {
45 //test conflicts
46 biMap.put("2", "one");
47 throw new Exception("BiMap should not accept non-unique value");
48 } catch (IllegalArgumentException e)
49 {
50 //expected
51 }
52 //test insert different value
53 biMap.put("1", "two");
54 assertEquals("two", biMap.get("1"));
55 assertEquals("1", inverse.get("two"));
56 //test remove
57 biMap.remove("1");
58 assertEquals(biMap.get("1"), null);
59 assertEquals(inverse.get("one"), null);
60 }
61 }
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.ArrayList;
23 import java.util.List;
24 import org.onemind.commons.java.datastructure.ClassSet;
25 import junit.framework.TestCase;
26 /**
27 * Testing for ClassSet
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: ClassSetTest.java,v 1.2 2004/08/26 12:33:09 thlee Exp $ $Name: $
30 */
31 public class ClassSetTest extends TestCase
32 {
33
34 public void testIsSubClasses()
35 {
36 ClassSet set = new ClassSet();
37 set.add(Number.class);
38 assertTrue(!set.isSubclassOfClasses(Object.class));
39 assertTrue(set.isSubclassOfClasses(Number.class));
40 }
41
42 public void testAddAll()
43 {
44 List l = new ArrayList();
45 l.add(Object.class);
46 l.add(Number.class);
47 ClassSet set = new ClassSet();
48 set.addAll(l);
49 l.add(new Object());
50 try
51 {
52 set.addAll(l);
53 throw new Exception("Object should have be accepted by addAll()");
54 } catch (Exception e)
55 {
56 //pass
57 }
58 }
59 }
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.List;
23 import junit.framework.TestCase;
24 import org.onemind.commons.java.datastructure.CounterQueue;
25 /**
26 * The test for counter queue
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: CounterQueueTest.java,v 1.2 2004/08/26 12:33:09 thlee Exp $ $Name: $
29 */
30 public class CounterQueueTest extends TestCase
31 {
32
33 public void testCounterQueue()
34 {
35 CounterQueue cq = new CounterQueue();
36 Object counter = new Object();
37 Object queuer1 = new Object();
38 Object queuer2 = new Object();
39 //just check for random counter object
40 assertEquals(cq.getQueue(new Object()).size(), 0);
41 //adding
42 cq.addToQueue(counter, queuer1);
43 cq.addToQueue(counter, queuer2);
44 //just check for random counter object
45 assertEquals(cq.getQueue(new Object()).size(), 0);
46 //test added result
47 List l = cq.getQueue(counter);
48 assertEquals(l.size(), 2);
49 assertEquals(l.get(0), queuer1);
50 assertEquals(l.get(1), queuer2);
51 //test remove next from queue
52 assertEquals(cq.removeNextFromQueue(counter), queuer1);
53 assertEquals(l.size(), 1);
54 //test remove from queuer
55 cq.removeFromQueue(counter, queuer2);
56 assertEquals(l.size(), 0);
57 }
58 }
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 import java.util.Map;
24 import junit.framework.TestCase;
25 public class DuoMapKeyTest extends TestCase
26 {
27
28 public void testKey()
29 {
30 Map m = new HashMap();
31 Object o1 = new Object();
32 Object o2 = new Object();
33 m.put(new DuoMapKey(null, null), o1);
34 assertEquals(m.get(new DuoMapKey(null, null)), o1);
35 m.put(new DuoMapKey("test1", "test2"), o2);
36 assertEquals(m.get(new DuoMapKey("test1", "test2")), o2);
37 assertEquals(m.get(new DuoMapKey("test2", "test2")), null);
38 }
39 }
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 org.onemind.commons.java.datastructure.InheritableValueMap;
23 import junit.framework.TestCase;
24 /**
25 * Test inherited value map
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: InheritableValueMapTest.java,v 1.2 2004/08/26 12:33:08 thlee Exp $ $Name: $
28 */
29 public class InheritableValueMapTest extends TestCase
30 {
31
32 public void testInheritedValueMap()
33 {
34 InheritableValueMap map = new InheritableValueMap();
35 Object numberValue = new Object();
36 // add in number mapping
37 map.put(Number.class, numberValue);
38 // test result
39 assertEquals(map.resolve(Number.class), numberValue);
40 assertEquals(map.resolve(Integer.class), numberValue);
41 // add in integer mapping
42 Object intValue = new Object();
43 map.put(Integer.class, intValue);
44 //test result
45 assertEquals(map.resolve(Number.class), numberValue);
46 assertEquals(map.resolve(Integer.class), intValue);
47 //test wrong argument
48 try
49 {
50 map.resolve(Object.class);
51 throw new Exception("Should not pass this");
52 } catch (Exception e)
53 {
54 //pass
55 }
56 }
57 }
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 org.onemind.commons.java.datastructure.LookupCache;
23 import junit.framework.TestCase;
24 /**
25 * Test for lookup cache
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: LookupCacheTest.java,v 1.2 2004/08/26 12:33:09 thlee Exp $ $Name: $
28 */
29 public class LookupCacheTest extends TestCase
30 {
31
32 /**
33 * A test implemement for the lookup cache
34 * @author TiongHiang Lee (thlee@onemindsoft.org)
35 * @version $Id: LookupCacheTest.java,v 1.2 2004/08/26 12:33:09 thlee Exp $ $Name: $
36 */
37 private class TestCacheImpl extends LookupCache
38 {
39
40 /**
41 * Only produce value if key is "One" {@inheritDoc}
42 */
43 protected Object produce(Object key)
44 {
45 if (key.equals("One"))
46 {
47 return new Integer("1");
48 } else
49 {
50 return null;
51 }
52 }
53 }
54
55 public void testLookupCache()
56 {
57 TestCacheImpl cache = new TestCacheImpl();
58 String one = "One";
59 String two = "Two";
60 assertFalse(cache.isInCache(one));
61 assertFalse(cache.isInCache(two));
62 assertFalse(cache.isInNegCache(one));
63 assertFalse(cache.isInNegCache(two));
64 cache.lookup("One");
65 cache.lookup("Two");
66 assertTrue(cache.isInCache(one));
67 assertTrue(cache.isInNegCache(two));
68 }
69 }
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.TreeSet;
23 import org.onemind.commons.java.datastructure.MruList;
24 import junit.framework.TestCase;
25 /**
26 * Test for MruList
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: MruListTest.java,v 1.2 2004/08/26 12:33:09 thlee Exp $ $Name: $
29 */
30 public class MruListTest extends TestCase
31 {
32
33 /**
34 * Test the MruEntry implementation
35 * @throws Exception if there's problem
36 */
37 public void testMruEntry() throws Exception
38 {
39 TreeSet set = new TreeSet();
40 Object first = new String("first");
41 Object second = new String("second");
42 MruList.MruEntry entry1 = new MruList.MruEntry(first, System.currentTimeMillis());
43 Thread.currentThread().sleep(20);
44 MruList.MruEntry entry2 = new MruList.MruEntry(second, System.currentTimeMillis());
45 set.add(entry1);
46 set.add(entry2);
47 assertEquals(set.iterator().next(), entry2);
48 System.out.println(set);
49 Thread.currentThread().sleep(20);
50 entry1.setLastAccessTime(System.currentTimeMillis());
51 set.remove(entry1);
52 set.add(entry1);
53 System.out.println(set);
54 assertEquals(set.iterator().next(), entry1);
55 }
56
57 /**
58 * Test the MruList
59 * @throws Exception if there's problem
60 */
61 public void testMruList() throws Exception
62 {
63 MruList list = new MruList();
64 Object first = new String("first");
65 Object second = new String("second");
66 list.add(first);
67 Thread.currentThread().sleep(20);
68 list.add(second);
69 System.out.println(list.iterator().next());
70 assertEquals(list.iterator().next(), second);
71 Thread.currentThread().sleep(20);
72 list.add(first);
73 assertEquals(list.iterator().next(), first);
74 }
75
76 /**
77 * Test truncation
78 */
79 public void testTruncate()
80 {
81 MruList list = new MruList(3, 0);
82 for (int i = 0; i < 10; i++)
83 {
84 Integer obj = new Integer(i);
85 list.add(obj);
86 }
87 assertEquals(list.size(), 3);
88 }
89 }
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 org.onemind.commons.java.datastructure.MruMap;
23 import junit.framework.TestCase;
24 /**
25 * Test for MruMap
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: MruMapTest.java,v 1.2 2004/08/26 12:33:08 thlee Exp $ $Name: $
28 */
29 public class MruMapTest extends TestCase
30 {
31 public void testMruMap() throws Exception
32 {
33 MruMap map = new MruMap(3, 0);
34 for (int i = 0; i < 10; i++)
35 {
36 Integer obj = new Integer(i);
37 Thread.sleep(200);
38 map.put(obj, obj);
39 }
40 assertEquals(map.size(), 3);
41 assertTrue(map.containsKey(new Integer(9)));
42 assertTrue(map.containsKey(new Integer(8)));
43 assertTrue(map.containsKey(new Integer(7)));
44 }
45 }
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 org.onemind.commons.java.datastructure.NametableStack;
23 import junit.framework.TestCase;
24 /**
25 * Test for nametable stack
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: NametableStackTest.java,v 1.3 2005/04/06 15:40:43 thlee Exp $ $Name: $
28 */
29 public class NametableStackTest extends TestCase
30 {
31
32 public void testCloseScope()
33 {
34 NametableStack stack = new NametableStack();
35 //add 0-4
36 for (int i = 0; i < 5; i++)
37 {
38 String name = String.valueOf(i);
39 stack.declare(name, name);
40 }
41 //open new scope
42 int scope = stack.newScope();
43 //add 5-9
44 for (int i = 5; i < 10; i++)
45 {
46 String name = String.valueOf(i);
47 stack.declare(name, name);
48 }
49 // check all values valid
50 for (int i = 0; i < 10; i++)
51 {
52 String name = String.valueOf(i);
53 assertEquals(stack.access(name), name);
54 }
55 //close scope
56 stack.closeScope(scope);
57 //check only 0-4 valid
58 for (int i = 5; i < 10; i++)
59 {
60 String name = String.valueOf(i);
61 assertFalse(stack.containsName(name));
62 }
63 for (int i = 0; i < 5; i++)
64 {
65 String name = String.valueOf(i);
66 assertEquals(stack.access(name), name);
67 }
68 }
69
70 public void testLocalScope()
71 {
72 NametableStack stack = new NametableStack();
73 //add 0-4
74 for (int i = 0; i < 5; i++)
75 {
76 String name = String.valueOf(i);
77 stack.declare(name, name);
78 }
79 //open new local scope
80 int scope = stack.newLocalScope();
81 //add 5-9
82 for (int i = 2; i < 7; i++)
83 {
84 String name = String.valueOf(i);
85 stack.declare(name, name);
86 }
87 // check all values valid
88 for (int i = 0; i < 7; i++)
89 {
90 String name = String.valueOf(i);
91 assertEquals(stack.access(name), name);
92 }
93 //close scope
94 stack.closeLocalScope(scope);
95 //check only 0-4 valid
96 for (int i = 5; i < 7; i++)
97 {
98 String name = String.valueOf(i);
99 assertFalse(stack.containsName(name));
100 }
101 for (int i = 0; i < 5; i++)
102 {
103 String name = String.valueOf(i);
104 assertEquals(stack.access(name), name);
105 }
106
107
108 }
109 }
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 org.onemind.commons.java.datastructure.Stack;
23 import junit.framework.TestCase;
24
25 /**
26 * Test for stack
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: StackTest.java,v 1.2 2004/08/26 12:33:08 thlee Exp $ $Name: $
29 */
30 public class StackTest extends TestCase
31 {
32
33 public void testStack()
34 {
35 Stack st = new Stack();
36 assertEquals(st.pushReturnSize(new Integer(1)), 0);
37 assertEquals(st.pushReturnSize(new Integer(2)), 1);
38 st.popUntil(1);
39 assertEquals(st.size(), 1);
40 assertTrue(st.contains(new Integer(1)));
41 }
42 }
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 import java.util.Map;
24 import org.onemind.commons.java.datastructure.TrackedMap;
25 import junit.framework.TestCase;
26 /**
27 * Test for TrackedMap
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: TrackedMapTest.java,v 1.2 2004/08/26 12:33:09 thlee Exp $ $Name: $
30 */
31 public class TrackedMapTest extends TestCase
32 {
33
34 public void testTrackedMap()
35 {
36 Object first = new String("first");
37 Object second = new String("second");
38 Object third = new String("third");
39 Map m = new HashMap();
40 m.put(first, first);
41
42 //start with first
43 TrackedMap map = new TrackedMap(m);
44 assertEquals(map.size(), 1);
45 assertEquals(map.keySet().size(), 1);
46 assertEquals(map.values().size(), 1);
47 //replace first
48 map.put(first, first);
49 assertTrue(map.hasChanges());
50 assertEquals(map.size(), 1);
51 assertEquals(map.keySet().size(), 1);
52 assertEquals(map.values().size(), 1);
53
54 //add second
55 map.put(second, second);
56 //assert that it's changed
57 assertTrue(map.hasChanges());
58 assertEquals(map.size(), 2);
59 assertEquals(map.keySet().size(), 2);
60 assertEquals(map.values().size(), 2);
61
62 //make up-to-date
63 map.makeUpToDate();
64 assertTrue(!map.hasChanges());
65 assertEquals(map.size(), 2);
66 assertEquals(map.keySet().size(), 2);
67 assertEquals(map.values().size(), 2);
68 }
69 }
0 <Properties>
1 <Property name="defaultvalue" value="default"/>
2 <Property name="shortvalue" type="short" value="1"/>
3 <Property name="intvalue" type="int" value="1"/>
4 <Property name="longvalue" type="long" value="1"/>
5 <Property name="floatvalue" type="float" value="1"/>
6 <Property name="doublevalue" type="double" value="1"/>
7 <Property name="charvalue" type="char" value="c"/>
8 <Property name="stringvalue" type="string" value="string"/>
9 <Property name="element" class="org.onemind.commons.java.datastructure.XmlPropertiesTest$TestElement" root="test" digest="true">
10 <TestElement>
11 </TestElement>
12 </Property>
13 </Properties>
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 org.onemind.commons.java.xml.digest.DefaultDigester;
23 import org.onemind.commons.java.xml.digest.SaxDigesterHandler;
24 import org.xml.sax.Attributes;
25 import org.xml.sax.SAXException;
26 import junit.framework.TestCase;
27 /**
28 * Xml properties
29 * @author TiongHiang Lee (thlee@onemindsoft.org)
30 * @version $Id: XmlPropertiesTest.java,v 1.3 2005/06/22 22:59:13 thlee Exp $ $Name: $
31 */
32 public class XmlPropertiesTest extends TestCase
33 {
34
35 public static class TestElement extends DefaultDigester
36 {
37
38 public boolean processed = false;
39
40 /**
41 * Constructor
42 */
43 public TestElement()
44 {
45 super("TestElement");
46 }
47
48 /**
49 * {@inheritDoc}
50 */
51 public void startDigest(SaxDigesterHandler handler, Attributes attrs) throws SAXException
52 {
53 processed = true;
54 }
55 }
56
57 public void testXmlProperties() throws Exception
58 {
59 XmlProperties prop = new XmlProperties(getClass().getResourceAsStream("XmlProperties.xml"));
60 assertEquals("default", prop.get("defaultvalue"));
61 assertEquals(new Short((short) 1), prop.get("shortvalue"));
62 assertEquals(new Integer(1), prop.get("intvalue"));
63 assertEquals(new Long(1), prop.get("longvalue"));
64 assertEquals(new Float(1), prop.get("floatvalue"));
65 assertEquals(new Double(1), prop.get("doublevalue"));
66 assertEquals(new Character('c'), prop.get("charvalue"));
67 assertEquals("string", prop.get("stringvalue"));
68 TestElement e = (TestElement) prop.get("element");
69 assertEquals(e.processed, true);
70 }
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.lang.ref;
21
22 import junit.framework.TestCase;
23 /**
24 * Testing SoftHashMap
25 * @author TiongHiang Lee (thlee@onemindsoft.org)
26 * @version $Id: SoftHashMapTest.java,v 1.2 2004/10/31 16:03:13 thlee Exp $ $Name: $
27 */
28 public class SoftHashMapTest extends TestCase
29 {
30
31 /** the map **/
32 private SoftHashMap _map;
33
34 /**
35 * {@inheritDoc}
36 */
37 public void setUp()
38 {
39 _map = new SoftHashMap();
40 }
41
42 /**
43 * Test the map
44 * @throws Exception
45 */
46 public void testMap() throws Exception
47 {
48 boolean collected = false;
49 for (int i = 1; i < 1000; i++)
50 {
51 _map.put(new Integer(i), new Integer(i));
52 if (_map.size() < i)
53 {
54 collected = true;
55 break;
56 }
57 System.gc();
58 }
59 if (!collected)
60 {
61 throw new Exception("SoftHashMap entries are not garbage collected");
62 }
63 }
64 }
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 package org.onemind.commons.java.lang.reflect;
20
21 import org.onemind.commons.java.lang.reflect.ClassLookupCache;
22 import junit.framework.TestCase;
23
24
25 /**
26 * Unit test the class lookup cache
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: ClassLooupCacheTest.java,v 1.4 2006/10/29 17:02:38 thlee Exp $ $Name: $
29 */
30 public class ClassLooupCacheTest extends TestCase
31 {
32 /** the cache **/
33 private ClassLookupCache _cache;
34
35 /**
36 * {@inheritDoc}
37 */
38 public void setUp()
39 {
40 _cache = new ClassLookupCache();
41 _cache.addImport("java.io.*");
42 }
43
44 /**
45 * Test lookup
46 */
47 public void testClassLookup() throws Exception
48 {
49 Class c = _cache.getClass("File");
50 assertEquals(c, java.io.File.class);
51 c = _cache.getClass("File1");
52 assertEquals(c, null);
53
54 //do it again to test the cache behavior.
55 //result verified through log4j output
56 assertTrue(_cache.isInCache("java.io.File"));
57 c = _cache.getClass("File1");
58 assertEquals(c, null);
59
60 c = _cache.getClass("Dummy");
61 assertEquals(c, null);
62
63 _cache.addImport("*");
64 c = _cache.getClass("Dummy");
65 assertEquals(Class.forName("Dummy"), c);
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.lang.reflect;
21
22 import java.lang.reflect.Method;
23 import junit.framework.TestCase;
24 /**
25 * Unit test for reflection utilities
26 * @author TiongHiang Lee (thlee@onemindsoft.org)
27 * @version $Id: ReflectUtilsTest.java,v 1.7 2006/08/02 00:07:24 thlee Exp $ $Name: $
28 */
29 public class ReflectUtilsTest extends TestCase
30 {
31
32 private Class[] _classNames = {java.lang.Object.class, java.lang.Integer.class, java.lang.Float.class, java.lang.Double.class,
33 java.lang.Long.class, java.lang.Boolean.class, java.lang.String.class, java.lang.Double.class, java.lang.Byte.class,
34 java.lang.Character.class, java.lang.Exception.class, java.lang.Class.class};
35
36 /** a test class * */
37 public static class TestClass
38 {
39
40 /**
41 * Static method
42 */
43 public static void staticMethod()
44 {
45 }
46
47 public String normalMethod(Object obj)
48 {
49 return "A";
50 //do nothing
51 }
52
53 public String normalMethod(Integer obj)
54 {
55 return "B";
56 //do nothing
57 }
58
59 public String normalMethod(String obj)
60 {
61 return "C";
62 //do nothing
63 }
64
65 public String similarMethod(short a)
66 {
67 return "short";
68 }
69
70 public String similarMethod(int a)
71 {
72 return "int";
73 }
74
75 public String similarMethod(long a)
76 {
77 return "long";
78 }
79 }
80
81 public static class TestSubClass extends TestClass
82 {
83 }
84
85 /** test the util * */
86 public void testStaticMethodInvocation() throws Exception
87 {
88 ReflectUtils.invoke(TestClass.class, "staticMethod", null);
89 ReflectUtils.invoke(TestSubClass.class, "staticMethod", null);
90 }
91
92 public void testClassMethodInvocation() throws Exception
93 {
94 ReflectUtils.invoke(new TestSubClass().getClass(), "getName", null);
95 ReflectUtils.invoke(new TestSubClass().getClass(), "getName", null);
96 }
97
98 public void testObjectMethodInvcation() throws Exception
99 {
100 ReflectUtils.invoke(new TestClass(), "normalMethod", new Object[]{null});
101 }
102
103 public void testMethodSearch() throws Exception
104 {
105 Object result = ReflectUtils.invoke(new TestSubClass(), "similarMethod", new Object[]{new Long(1)});
106 assertTrue(result.equals("long"));
107 result = ReflectUtils.invoke(new TestSubClass(), "similarMethod", new Object[]{new Integer(1)});
108 assertTrue(result.equals("int"));
109 result = ReflectUtils.invoke(new TestSubClass(), "similarMethod", new Object[]{new Short((short) 1)});
110 assertTrue(result.equals("short"));
111 Object args[] = new Object[] { new Integer(1), new Integer(1) } ;
112 ReflectUtils.invoke(Math.class, "pow", args);
113 }
114
115 public void testClassCache() throws Exception
116 {
117 long start = System.currentTimeMillis();
118 ReflectUtils.setClassCaching(false);
119 for (int i = 0; i < 10000; i++)
120 {
121 lookForClasses();
122 }
123 long end = System.currentTimeMillis();
124 System.out.println("Time used for class lookup without caching = " + (end - start));
125 start = System.currentTimeMillis();
126 ReflectUtils.setClassCaching(true);
127 start = System.currentTimeMillis();
128 for (int i = 0; i < 10000; i++)
129 {
130 lookForClasses();
131 }
132 end = System.currentTimeMillis();
133 System.out.println("Time used for class lookup with caching = " + (end - start));
134 }
135
136 public void testMethodCache() throws Exception
137 {
138 long start = System.currentTimeMillis();
139 ReflectUtils.setMethodCaching(false);
140 for (int i = 0; i < 10000; i++)
141 {
142 lookForMethods();
143 }
144 long end = System.currentTimeMillis();
145 System.out.println("Time used for method lookup without caching = " + (end - start));
146 start = System.currentTimeMillis();
147 ReflectUtils.setMethodCaching(true);
148 start = System.currentTimeMillis();
149 for (int i = 0; i < 10000; i++)
150 {
151 lookForMethods();
152 }
153 end = System.currentTimeMillis();
154 System.out.println("Time used for method lookup with caching = " + (end - start));
155 }
156
157 private void lookForClasses() throws Exception
158 {
159 for (int i = 0; i < _classNames.length; i++)
160 {
161 ReflectUtils.getClass(_classNames[i].getName());
162 }
163 }
164
165 private void lookForMethods() throws Exception
166 {
167 for (int i = 0; i < _classNames.length; i++)
168 {
169 ReflectUtils.getMethod(_classNames[i], "equals", new Class[]{Object.class});
170 }
171 }
172
173 public void testPrimitiveArgumentCheck() throws Exception
174 {
175 assertTrue(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Object[]{new Long(1)}));
176 assertTrue(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Object[]{new Integer(1)}));
177 assertFalse(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Object[]{new Float(1.5)}));
178 assertFalse(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Object[]{new Double(1.5)}));
179 assertTrue(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Class[]{Long.class}));
180 assertTrue(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Class[]{Integer.class}));
181 assertFalse(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Class[]{Float.class}));
182 assertFalse(ReflectUtils.isCompatible(new Class[]{Long.TYPE}, new Class[]{Double.class}));
183 }
184
185 public static void main(String[] args) throws Exception
186 {
187 ReflectUtilsTest test = new ReflectUtilsTest();
188 test.testClassCache();
189 }
190 }
0
1 package org.onemind.commons.java.pattern;
2
3 import junit.framework.TestCase;
4 /**
5 * @author TiongHiang Lee (tlee@i2rd.com)
6 * @version $Id: DynamicVisitorTest.java,v 1.1 2004/10/31 16:03:44 thlee Exp $ $Name: $
7 */
8 public class DynamicVisitorTest extends TestCase
9 {
10
11 private class TestBaseClass
12 {
13 }
14
15 public class TestClass extends TestBaseClass
16 {
17 }
18
19 public class TestSubClass extends TestClass
20 {
21 }
22
23 public class TestVisitor extends DynamicVisitor
24 {
25
26 /**
27 * {@inheritDoc}
28 */
29 protected void initNodeHandlers()
30 {
31 addMethodNodeHandler(TestBaseClass.class, "visit");
32 addMethodNodeHandler(TestClass.class, "visit");
33 addMethodNodeHandler(TestSubClass.class, "visit");
34 }
35
36 public Object visit(TestBaseClass obj, Object[] data)
37 {
38 assertTrue(obj.getClass()==TestBaseClass.class);
39 return null;
40 }
41
42 public Object visit(TestClass obj, Object[] data)
43 {
44 assertTrue(obj.getClass()==TestClass.class);
45 return null;
46 }
47
48 public Object visit(TestSubClass obj, Object[] data)
49 {
50 assertTrue(obj.getClass()==TestSubClass.class);
51 return null;
52 }
53 };
54
55 public void testVisitor()
56 {
57 TestVisitor visitor = new TestVisitor();
58 }
59 }
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.util;
21
22 import org.onemind.commons.java.util.FileUtils;
23 import junit.framework.TestCase;
24
25 /**
26 * Test for utils test
27 * @author TiongHiang Lee (thlee@onemindsoft.org)
28 * @version $Id: FileUtilsTest.java,v 1.2 2004/08/26 12:33:17 thlee Exp $ $Name: $
29 */
30 public class FileUtilsTest extends TestCase
31 {
32
33 public void testFileUtils()
34 {
35 assertEquals(FileUtils.concatFilePath("/test", "test1"), "/test/test1");
36 assertEquals(FileUtils.concatFilePath("/test", "/test1"), "/test/test1");
37 }
38 }
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.util;
21
22 import java.util.ArrayList;
23 import java.util.List;
24 import org.onemind.commons.java.util.StringUtils;
25 import junit.framework.TestCase;
26 /**
27 * Test for string utilities
28 * @author TiongHiang Lee (thlee@onemindsoft.org)
29 * @version $Id: StringUtilsTest.java,v 1.2 2004/08/26 12:33:17 thlee Exp $ $Name: $
30 */
31 public class StringUtilsTest extends TestCase
32 {
33
34 public void testConcatCollection()
35 {
36 List l = new ArrayList();
37 l.add(new String("first"));
38 l.add(new String("second"));
39 l.add(new String("third"));
40 String result = StringUtils.concat(l, ",");
41 assertEquals(result, "first,second,third");
42 }
43
44 public void testSubStringAfterLast()
45 {
46 String result = StringUtils.substringAfter("abcdefg", "cd");
47 assertEquals(result, "efg");
48 }
49
50 public void testSubStringBeforeLast()
51 {
52 String result = StringUtils.substringBeforeLast("abcdefg", "cd");
53 assertEquals(result, "ab");
54 }
55 }
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@thinklient.org
18 */
19
20 package org.onemind.commons.java.xml.digest;
21
22 import java.io.InputStream;
23 import javax.xml.parsers.SAXParser;
24 import javax.xml.parsers.SAXParserFactory;
25 import junit.framework.TestCase;
26 import org.xml.sax.Attributes;
27 import org.xml.sax.SAXException;
28 /**
29 * SaxDigester test. The model is with exactly one "RootElement" which can have 0-1 "Element" that can any random "SubElement1" and
30 * "SubElement2"
31 * @author TiongHiang Lee (thlee@thinklient.org)
32 * @version $Id: SaxDigesterTest.java,v 1.4 2005/04/26 17:46:39 thlee Exp $ $Name: $
33 */
34 public class SaxDigesterTest extends TestCase
35 {
36
37 /**
38 * Root element digester
39 */
40 public class TestElementDigester extends DefaultDigester
41 {
42
43 /** the count start is called**/
44 int startCount;
45
46 /** the count end is called **/
47 int endCount;
48
49 /** the count characters is called **/
50 int charCount;
51
52 /**
53 * {@inheritDoc}
54 */
55 public TestElementDigester(String str)
56 {
57 super(str);
58 }
59
60 /**
61 * {@inheritDoc}
62 */
63 public void startDigest(SaxDigesterHandler handler, Attributes attrs) throws SAXException
64 {
65 startCount++;
66 //System.out.println("Starting " + handler.getCurrentPath());
67 }
68
69 /**
70 * {@inheritDoc}
71 */
72 public void endDigest(SaxDigesterHandler handler) throws SAXException
73 {
74 endCount++;
75 //System.out.println("Ending " + handler.getCurrentPath());
76 }
77
78 /**
79 * {@inheritDoc}
80 */
81 public void characters(SaxDigesterHandler handler, char[] chars, int offset, int length) throws SAXException
82 {
83 charCount++;
84 //System.out.println("Character " + handler.getCurrentPath());
85 }
86 }
87
88 /**
89 * parse the file with the handler
90 * @throws Exception
91 */
92 private void _testHandler(InputStream in, SaxDigesterHandler handler) throws Exception
93 {
94 SAXParserFactory factory = SAXParserFactory.newInstance();
95 // Parse the input
96 SAXParser saxParser = factory.newSAXParser();
97 saxParser.parse(in, handler);
98 }
99
100 /**
101 * Test when there's one element
102 * @throws Exception if there's exception
103 */
104 public void testOneElement() throws Exception
105 {
106 SaxDigesterHandler handler = new SaxDigesterHandler();
107 TestElementDigester rootElement = new TestElementDigester("RootElement");
108 TestElementDigester rootElement1 = new TestElementDigester("RootElment1");
109 TestElementDigester subElement1 = new TestElementDigester("SubElement1");
110 handler.addDigester(rootElement);
111 handler.addDigester(rootElement1);
112 handler.addDigester("RootElement/Element1", subElement1);
113 _testHandler(getClass().getResourceAsStream("SaxDigesterTest.xml"), handler);
114 assertTrue(rootElement.startCount == 1);
115 assertTrue(rootElement.endCount == 1);
116 assertTrue(rootElement1.startCount == 0);
117 assertTrue(rootElement1.endCount == 0);
118 assertTrue(subElement1.startCount == 2);
119 assertTrue(subElement1.endCount == 2);
120 }
121 }
0 <?xml version='1.0' encoding='UTF-8'?>
1
2 <RootElement>
3 <Element1 attr="a">
4 <SubElement1 attr="b"> asdfdsf
5 </SubElement1>
6 <SubElement1>
7 </SubElement1>
8 </Element1>
9 </RootElement>