*** empty log message ***

This commit is contained in:
Eric J. Bowersox
2003-05-20 03:25:31 +00:00
commit b80fa05ed1
682 changed files with 85738 additions and 0 deletions

View File

@@ -0,0 +1,160 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
/**
* A class which performs the equivalent of <CODE>String.indexOf(char)</CODE>, but using
* multiple characters. It locates the first instance within a string of <EM>any</EM> of
* the specified characters.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public final class AnyCharMatcher
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private char[] charset; // the set of characters to look for
private int[] locs; // a temporary array used for locations
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
/**
* Creates a new character matcher that matches the specified characters.
*
* @param charset The set of characters to be matched by this object, expressed as a character array.
*/
public AnyCharMatcher(char[] charset)
{
this.charset = charset;
this.locs = new int[charset.length];
} // end constructor
/**
* Creates a new character matcher that matches the specified characters.
*
* @param charset The set of characters to be matched by this object, expressed as a string.
*/
public AnyCharMatcher(String charset)
{
this.charset = charset.toCharArray();
this.locs = new int[charset.length()];
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the offset within the string of the first instance of any character in this
* character set.
*
* @param str The string to look through. If this parameter is <B><CODE>null</CODE></B>,
* the method returns -1.
* @return The 0-based index of the first instance of any character from this character
* matcher within <CODE>str</CODE>. If <CODE>str</CODE> contains no instances of
* any character from this character matcher, -1 is returned.
*/
public final int get(String str)
{
if (str==null)
return -1;
int numindexes = 0;
int i;
for (i=0; i<charset.length; i++)
{ // locate the index of the first HTML character
int tmp = str.indexOf(charset[i]);
if (tmp>=0)
locs[numindexes++] = tmp;
} // end for
if (numindexes==0)
return -1; // no characters found
else if (numindexes==1)
return locs[0]; // only one found
int rc = locs[0];
for (i=1; i<numindexes; i++)
{ // this loop determines the lowest possible return value
if (rc==0)
return 0; // can't get any lower!
if (locs[i]<rc)
rc = locs[i]; // this is now the lowest
} // end for
return rc;
} // end get
/**
* Returns the offset within the string of the last instance of any character in this
* character set.
*
* @param str The string to look through. If this parameter is <B><CODE>null</CODE></B>,
* the method returns -1.
* @return The 0-based index of the last instance of any character from this character
* matcher within <CODE>str</CODE>. If <CODE>str</CODE> contains no instances of
* any character from this character matcher, -1 is returned.
*/
public final int getLast(String str)
{
if (str==null)
return -1;
int numindexes = 0;
int i;
for (i=0; i<charset.length; i++)
{ // locate the index of the first HTML character
int tmp = str.lastIndexOf(charset[i]);
if (tmp>=0)
locs[numindexes++] = tmp;
} // end for
if (numindexes==0)
return -1; // no characters found
else if (numindexes==1)
return locs[0]; // only one found
int rc = locs[0];
int limit = str.length() - 1;
for (i=1; i<numindexes; i++)
{ // this loop determines the highest possible return value
if (rc==limit)
return limit; // can't get any higher!
if (locs[i]>rc)
rc = locs[i]; // this is now the highest
} // end for
return rc;
} // end getLast
} // end class AnyCharMatcher

View File

@@ -0,0 +1,19 @@
# The contents of this file are subject to the Mozilla Public License Version 1.1
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
#
# Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
# WARRANTY OF ANY KIND, either express or implied. See the License for the specific
# language governing rights and limitations under the License.
#
# The Original Code is the Venice Web Communities System.
#
# The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
# for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
# Copyright (C) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# ---------------------------------------------------------------------------------
# This file has been localized for the en_US locale
values.true=1|true|yes|on
values.false=0|false|no|off

View File

@@ -0,0 +1,159 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
/**
* A utility class used by <CODE>International</CODE> that stores a country code and name pair.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
* @see International
*/
public final class Country implements Comparable
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_code; // the country code
private String m_name; // the country name
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new <CODE>Country</CODE> object.
*
* @param code The country code.
* @param name The country name.
*/
Country(String code, String name)
{
m_code = code.trim().toUpperCase();
m_name = name.trim();
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
/**
* Indicates whether some other object is "equal to" this one.
*
* @param o The reference object with which to compare.
* @return <CODE>true</CODE> if this object is the same as the <CODE>o</CODE> argument; <CODE>false</CODE> otherwise.
*/
public boolean equals(Object o)
{
if ((o==null) || !(o instanceof Country))
return false;
if (this==(Country)o)
return true;
Country other = (Country)o;
return m_code.equals(other.m_code);
} // end equals
/**
* Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those
* provided by <CODE>java.util.Hashtable</CODE>.
*
* @return A hash code value for this object.
*/
public int hashCode()
{
return m_code.hashCode();
} // end hashCode
/**
* Returns a string representation of the object. In general, the <CODE>toString</CODE> method returns a string
* that "textually represents" this object.
*
* @return A string representation of the object.
*/
public String toString()
{
return m_name + " [" + m_code + "]";
} // end toString
/*--------------------------------------------------------------------------------
* Implementations from interface Comparable
*--------------------------------------------------------------------------------
*/
/**
* Compares this object with the specified object for order. Returns a negative integer, zero, or a positive
* integer as this object is less than, equal to, or greater than the specified object. <CODE>Country</CODE>
* objects are compared on their country name.
*
* @param o The Object to be compared.
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than
* the specified object.
* @exception java.lang.ClassCastException If the specified object's type prevents it from being compared to
* this Object.
*/
public int compareTo(Object o)
{
if (o==null)
return 1;
if (o instanceof Country)
{ // compare country names
Country c = (Country)o;
return m_name.compareTo(c.m_name);
} // end if
return m_name.compareTo(o.toString());
} // end compareTo
/*--------------------------------------------------------------------------------
* External getters
*--------------------------------------------------------------------------------
*/
/**
* Returns the 2-letter country code for this country.
*
* @return The 2-letter country code for this country.
*/
public final String getCode()
{
return m_code;
} // end code
/**
* Returns the name of this country.
*
* @return The name of this country.
*/
public final String getName()
{
return m_name;
} // end name
} // end class Country

View File

@@ -0,0 +1,329 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.lang.ref.*;
import java.util.*;
/**
* A class implementing a memory-sensitive cache. The cache is an LRU cache which uses two size limits,
* the <EM>soft limit</EM> and the <EM>hard limit</EM>. The soft limit dictates the maximum size of the
* cache; all elements in the cache have <CODE>SoftReference</CODE>s to them, which allows the JVM to expel
* them from memory if necessary. However, the most recent elements in the cache, up to the hard limit,
* have ordinary references on them, which prevents them from being expelled. Therefore, under low memory
* conditions, all elements in the cache may be discarded except for the most recent ones.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class HardSoftCache
{
/*--------------------------------------------------------------------------------
* Internal class to hold the hard hash entries
*--------------------------------------------------------------------------------
*/
private static class HardHashMap extends LinkedHashMap
{
/*====================================================================
* Attributes
*====================================================================
*/
private int m_maxsize; // maximum size of the cache
/*====================================================================
* Constructor
*====================================================================
*/
private HardHashMap(int capacity)
{
super(capacity+2,0.95F,true);
m_maxsize = capacity;
} // end constructor
/*====================================================================
* Overrides from class LinkedHashMap
*====================================================================
*/
protected boolean removeEldestEntry(Map.Entry eldest)
{
return (this.size()>m_maxsize);
} // end removeEldestEntry
} // end class HardHashMap
/*--------------------------------------------------------------------------------
* Internal class to hold the soft hash entries
*--------------------------------------------------------------------------------
*/
private static class SoftHashMap extends LinkedHashMap
{
/*====================================================================
* Attributes
*====================================================================
*/
private int m_maxsize; // maximum size of the cache
/*====================================================================
* Constructor
*====================================================================
*/
private SoftHashMap(int capacity)
{
super(capacity+2,0.95F,true);
m_maxsize = capacity;
} // end constructor
/*====================================================================
* Overrides from class HashMap
*====================================================================
*/
public Object put(Object key, Object value)
{
SoftReference newref = new SoftReference(value);
Reference r = (Reference)(super.put(key,newref));
Object rc = null;
if (r!=null)
{ // get the old object
rc = r.get();
r.clear();
} // end if
return rc;
} // end put
public void putAll(Map t)
{
Iterator it = t.entrySet().iterator();
while (it.hasNext())
{ // run each item through our modified put()
Map.Entry ntry = (Map.Entry)(it.next());
this.put(ntry.getKey(),ntry.getValue());
} // end while
} // end putAll
public Object remove(Object key)
{
Reference r = (Reference)(super.remove(key));
Object rc = null;
if (r!=null)
{ // get the old object
rc = r.get();
r.clear();
} // end if
return rc;
} // end remove
/*====================================================================
* Overrides from class LinkedHashMap
*====================================================================
*/
public void clear()
{
Iterator it = this.values().iterator();
while (it.hasNext())
{ // dump all the references we contain
Reference r = (Reference)(it.next());
r.clear();
} // end while
super.clear();
} // end clear
public Object get(Object key)
{
Reference r = (Reference)(super.get(key));
if (r==null)
return null;
Object rc = r.get();
if (rc==null)
{ // reference has been dumped - remove it from the map
super.remove(key);
r.clear();
} // end if
return rc;
} // end get
protected boolean removeEldestEntry(Map.Entry eldest)
{
if (this.size()<=m_maxsize)
return false;
Reference r = (Reference)(eldest.getValue());
r.clear();
return true;
} // end removeEldestEntry
} // end class SoftHashMap
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private HardHashMap m_hard_map; // the "hard map"
private SoftHashMap m_soft_map; // the "soft map"
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new cache object.
*
* @param hard_limit The "hard limit" for this cache. Has a minimum value of 1.
* @param soft_limit The "soft limit" for this cache. Has a minimum value of 2 times the value of the
* "hard limit."
*/
public HardSoftCache(int hard_limit, int soft_limit)
{
// Pre-condition the input parameters.
if (hard_limit<1)
hard_limit = 1;
if (soft_limit<(hard_limit * 2))
soft_limit = hard_limit * 2;
m_hard_map = new HardHashMap(hard_limit);
m_soft_map = new SoftHashMap(soft_limit);
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the value to which this cache maps the specified key. Returns <CODE>null</CODE> if the cache
* contains no mapping for this key.
*
* @param key The key whose associated value is to be returned.
* @return The value to which this cache maps the specified key.
*/
public synchronized Object get(Object key)
{
if (key==null)
throw new NullPointerException("HardSoftCache.get");
Object hard_rc = m_hard_map.get(key);
Object soft_rc = m_soft_map.get(key);
return ((hard_rc!=null) ? hard_rc : soft_rc);
} // end get
/**
* Associates the specified value with the specified key in this cache. If the cache previously contained a
* mapping for this key, the old value is replaced.
*
* @param key The key with which the specified value is to be associated.
* @param value The value to be associated with the specified key.
*/
public synchronized void put(Object key, Object value)
{
if (key==null)
throw new NullPointerException("HardSoftCache.put(key)");
if (value==null)
throw new NullPointerException("HardSoftCache.put(value)");
m_hard_map.put(key,value);
m_soft_map.put(key,value);
} // end put
/**
* Removes the mapping for this key from this cache if present.
*
* @param key The key whose mapping is to be removed from the map.
*/
public synchronized void remove(Object key)
{
if (key==null)
throw new NullPointerException("HardSoftCache.remove");
m_hard_map.remove(key);
m_soft_map.remove(key);
} // end remove
/**
* Returns the number of key-value mappings in this cache.
*
* @return The number of key-value mappings in this cache.
*/
public synchronized int size()
{
return m_soft_map.size();
} // end size
/**
* Returns <CODE>true</CODE> if this cache contains no key-value mappings.
*
* @return <CODE>true</CODE> if this cache contains no key-value mappings.
*/
public synchronized boolean isEmpty()
{
return m_hard_map.isEmpty();
} // end isEmpty
/**
* Removes all mappings from this cache.
*/
public synchronized void clear()
{
m_hard_map.clear();
m_soft_map.clear();
} // end clear
/**
* Returns <CODE>true</CODE> if this cache contains a mapping for the specified key.
*
* @param key The key whose presence in this cache is to be tested.
* @return <CODE>true</CODE> if this cache contains a mapping for the specified key.
*/
public synchronized boolean containsKey(Object key)
{
if (key==null)
throw new NullPointerException("HardSoftCache.containsKey");
return (m_soft_map.get(key)!=null);
} // end containsKey
} // end class HardSoftCache

View File

@@ -0,0 +1,378 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.io.*;
/**
* A collection of IO-related static methods which are useful in various contexts.<P>
* Some of the concepts in this class have been borrowed from Apache Jakarta Avalon Excalibur 4.0.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class IOUtils
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
/**
* The default buffer size to use for copying, if none is specified.
*/
public static int DEFAULT_BUFSIZE = 4096;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* IOUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>IOUtils.shutdown(stm);</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.
*/
public IOUtils()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
/**
* Closes an input stream cleanly, without throwing an exception.
*
* @param stm The stream to be closed.
* @see java.io.InputStream#close()
*/
public static void shutdown(InputStream stm)
{
try
{ // close the stream
stm.close();
} // end try
catch (IOException e)
{ // throw away the exception
} // end catch
} // end shutdown
/**
* Closes an output stream cleanly, without throwing an exception.
*
* @param stm The stream to be closed.
* @see java.io.OutputStream#close()
*/
public static void shutdown(OutputStream stm)
{
try
{ // close the stream
stm.close();
} // end try
catch (IOException e)
{ // throw away the exception
} // end catch
} // end shutdown
/**
* Closes an input reader cleanly, without throwing an exception.
*
* @param stm The stream to be closed.
* @see java.io.Reader#close()
*/
public static void shutdown(Reader rdr)
{
try
{ // close the stream
rdr.close();
} // end try
catch (IOException e)
{ // throw away the exception
} // end catch
} // end shutdown
/**
* Closes an output reader cleanly, without throwing an exception.
*
* @param stm The stream to be closed.
* @see java.io.Writer#close()
*/
public static void shutdown(Writer wr)
{
try
{ // close the stream
wr.close();
} // end try
catch (IOException e)
{ // throw away the exception
} // end catch
} // end shutdown
/**
* Copies the contents of the given input stream to the given output stream.
*
* @param input The stream to copy binary data from.
* @param output The stream to copy binary data to.
* @param bufsize The size of the buffer to allocate for copying.
* @exception java.io.IOException If an exception occurred while reading or writing data.
*/
public static void copy(InputStream input, OutputStream output, int bufsize) throws IOException
{
byte[] buffer = new byte[bufsize];
int rd = input.read(buffer);
while (rd>=0)
{ // simple read-write loop to shove data out the door
if (rd>0)
output.write(buffer,0,rd);
rd = input.read(buffer);
} // end while
} // end copy
/**
* Copies the contents of the given input stream to the given output stream. Uses a default
* buffer size.
*
* @param input The stream to copy binary data from.
* @param output The stream to copy binary data to.
* @exception java.io.IOException If an exception occurred while reading or writing data.
* @see #DEFAULT_BUFSIZE
* @see #copy(java.io.InputStream,java.io.OutputStream,int)
*/
public static void copy(InputStream input, OutputStream output) throws IOException
{
copy(input,output,DEFAULT_BUFSIZE);
} // end copy
/**
* Takes the contents of an input stream and returns it as an array of bytes.
*
* @param input The stream to load binary data from.
* @param bufsize The size of the buffer to allocate for copying.
* @return A new byte array containing the contents of the specified input stream.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #copy(java.io.InputStream,java.io.OutputStream,int)
*/
public static byte[] load(InputStream input, int bufsize) throws IOException
{
ByteArrayOutputStream stm = new ByteArrayOutputStream();
try
{ // copy the data to the input stream
copy(input,stm,bufsize);
return stm.toByteArray();
} // end try
finally
{ // close our byte array stream before we go
shutdown(stm);
} // end finally
} // end load
/**
* Takes the contents of an input stream and returns it as an array of bytes. Uses a default
* buffer size.
*
* @param input The stream to load binary data from.
* @return A new byte array containing the contents of the specified input stream.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #DEFAULT_BUFSIZE
* @see #load(java.io.InputStream,int)
*/
public static byte[] load(InputStream input) throws IOException
{
return load(input,DEFAULT_BUFSIZE);
} // end load
/**
* Takes the contents of a binary file and returns it as an array of bytes.
*
* @param file The file to load binary data from.
* @param bufsize The size of the buffer to allocate for copying.
* @return A new byte array containing the contents of the specified file.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #load(java.io.InputStream,int)
*/
public static byte[] loadBinary(File file, int bufsize) throws IOException
{
FileInputStream stm = new FileInputStream(file);
try
{ // now just load from the stream
return load(stm,bufsize);
} // end try
finally
{ // close the file before we leave
shutdown(stm);
} // end finally
} // end loadBinary
/**
* Takes the contents of a binary file and returns it as an array of bytes. Uses a default
* buffer size.
*
* @param file The file to load binary data from.
* @return A new byte array containing the contents of the specified file.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #DEFAULT_BUFSIZE
* @see #loadBinary(java.io.File,int)
*/
public static byte[] loadBinary(File file) throws IOException
{
return loadBinary(file,DEFAULT_BUFSIZE);
} // end loadBinary
/**
* Copies the contents of the given input reader to the given output writer.
*
* @param input The reader to copy character data from.
* @param output The writer to copy character data to.
* @param bufsize The size of the buffer to allocate for copying.
* @exception java.io.IOException If an exception occurred while reading or writing data.
*/
public static void copy(Reader input, Writer output, int bufsize) throws IOException
{
char[] buffer = new char[bufsize];
int rd = input.read(buffer);
while (rd>=0)
{ // simple read-write loop to shove data out the door
if (rd>0)
output.write(buffer,0,rd);
rd = input.read(buffer);
} // end while
} // end copy
/**
* Copies the contents of the given input reader to the given output writer. Uses a default
* buffer size.
*
* @param input The reader to copy character data from.
* @param output The writer to copy character data to.
* @exception java.io.IOException If an exception occurred while reading or writing data.
* @see #DEFAULT_BUFSIZE
* @see #copy(java.io.Reader,java.io.Writer,int)
*/
public static void copy(Reader input, Writer output) throws IOException
{
copy(input,output,DEFAULT_BUFSIZE);
} // end copy
/**
* Takes the contents of an input reader and returns it as a <CODE>StringBuffer</CODE>.
*
* @param input The reader to copy character data from.
* @param bufsize The size of the buffer to allocate for copying.
* @return A new <CODE>StringBuffer</CODE> containing the contents of the specified reader.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #copy(java.io.Reader,java.io.Writer,int)
*/
public static StringBuffer load(Reader input, int bufsize) throws IOException
{
StringWriter wr = new StringWriter();
try
{ // copy from reader to StringWriter
copy(input,wr,bufsize);
return wr.getBuffer();
} // end try
finally
{ // make sure and close the StringWriter before we go
shutdown(wr);
} // end finally
} // end load
/**
* Takes the contents of an input reader and returns it as a <CODE>StringBuffer</CODE>. Uses a
* default buffer size.
*
* @param input The reader to copy character data from.
* @return A new <CODE>StringBuffer</CODE> containing the contents of the specified reader.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #DEFAULT_BUFSIZE
* @see #load(java.io.Reader,int)
*/
public static StringBuffer load(Reader input) throws IOException
{
return load(input,DEFAULT_BUFSIZE);
} // end load
/**
* Takes the contents of a text file and returns it as a <CODE>StringBuffer</CODE>.
*
* @param file The file to copy text from.
* @param bufsize The size of the buffer to allocate for copying.
* @return A new <CODE>StringBuffer</CODE> containing the contents of the specified text file.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #load(java.io.Reader,int)
*/
public static StringBuffer loadText(File file, int bufsize) throws IOException
{
FileReader rdr = new FileReader(file);
try
{ // load from the string reader
return load(rdr,bufsize);
} // end try
finally
{ // make sure and close the reader before we go
shutdown(rdr);
} // end finally
} // end load
/**
* Takes the contents of a text file and returns it as a <CODE>StringBuffer</CODE>.
*
* @param file The file to copy text from.
* @return A new <CODE>StringBuffer</CODE> containing the contents of the specified text file.
* @exception java.io.IOException If an exception occurred while reading data.
* @see #DEFAULT_BUFSIZE
* @see #loadText(java.io.File,int)
*/
public static StringBuffer loadText(File file) throws IOException
{
return loadText(file,DEFAULT_BUFSIZE);
} // end load
} // end class IOUtils

View File

@@ -0,0 +1,267 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.io.*;
import java.util.*;
/**
* A class which centralizes a number of "international" resources, such as locales,
* country lists, and language lists.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class International
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static International self = new International(); // me
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private List country_list = null; // list of Country objects
private Map country_map = null; // mapping from codes to Country objects
private List language_list = null; // list of Language objects
private Map language_map = null; // mapping from codes to Language objects
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new instance of the <CODE>International</CODE> object. Only one instance
* of this object is ever created.
*/
private International()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* Internal operations
*--------------------------------------------------------------------------------
*/
/**
* Loads the internal list of countries from a resource file.
*
* @exception RuntimeException If an I/O error occurred while loading the country list.
*/
private synchronized void loadCountryList()
{
if ((country_list!=null) || (country_map!=null))
return; // already loaded
// Create temporary list and map to hold read data.
ArrayList tmp_list = new ArrayList();
HashMap tmp_map = new HashMap();
try
{ // Load the country properties file.
BufferedReader data =
new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("countries.properties")));
String l; // temporary line
while ((l = data.readLine())!=null)
{ // read lines from the properties file
l = l.trim();
if ((l.length()==0) || (l.startsWith("#")))
continue; // blank line or comment line
int pos = l.indexOf('=');
if (pos<0)
continue; // no properties - just forget this line
Country c = new Country(l.substring(0,pos),l.substring(pos+1));
tmp_list.add(c);
tmp_map.put(c.getCode(),c);
} // end while
} // end try
catch (IOException e)
{ // IO error loading country properties...
throw new RuntimeException("Error loading country.properties: " + e.getMessage());
} // end catch
// Set up the lists, which are considered "unmodifiable."
tmp_list.trimToSize();
country_list = Collections.unmodifiableList(tmp_list);
country_map = Collections.unmodifiableMap(tmp_map);
} // end loadCountryList
/**
* Loads the internal list of languages from a resource file.
*
* @exception RuntimeException If an I/O error occurred while loading the language list.
*/
private synchronized void loadLanguageList()
{
if ((language_list!=null) || (language_map!=null))
return; // already loaded
// Create temporary list and map to hold read data.
ArrayList tmp_list = new ArrayList();
HashMap tmp_map = new HashMap();
try
{ // Load the language properties file.
BufferedReader data =
new BufferedReader(new InputStreamReader(getClass().getResourceAsStream("languages.properties")));
String l; // temporary line
while ((l = data.readLine())!=null)
{ // read lines from the properties file
l = l.trim();
if ((l.length()==0) || (l.startsWith("#")))
continue; // blank line or comment line
int pos = l.indexOf('=');
if (pos<0)
continue; // no properties - just forget this line
Language lng = new Language(l.substring(0,pos),l.substring(pos+1));
tmp_list.add(lng);
tmp_map.put(lng.getCode(),lng);
} // end while
} // end try
catch (IOException e)
{ // IO error loading language properties...
throw new RuntimeException("Error loading language.properties: " + e.getMessage());
} // end catch
// Set up the lists, which are considered "unmodifiable."
tmp_list.trimToSize();
language_list = Collections.unmodifiableList(tmp_list);
language_map = Collections.unmodifiableMap(tmp_map);
} // end loadLanguageList
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the list of defined countries.
*
* @return The list of <CODE>Country</CODE> objects that are currently defined.
*/
public List getCountryList()
{
loadCountryList();
return country_list;
} // end getCountryList
/**
* Returns the <CODE>Country</CODE> object with the specified code.
*
* @param code The country code to match.
* @return The matching <CODE>Country</CODE> object, or <CODE>null</CODE> if no country matched.
*/
public Country getCountryForCode(String code)
{
if (code==null)
return null;
loadCountryList();
return (Country)(country_map.get(code.trim().toUpperCase()));
} // end getCountryForCode
/**
* Returns the list of defined languages.
*
* @return The list of <CODE>Language</CODE> objects that are currently defined.
*/
public List getLanguageList()
{
loadLanguageList();
return language_list;
} // end getLanguageList
/**
* Returns the <CODE>Language</CODE> object with the specified code.
*
* @param code The language code to match.
* @return The matching <CODE>Language</CODE> object, or <CODE>null</CODE> if no language matched.
*/
public Language getLanguageForCode(String code)
{
if (code==null)
return null;
loadLanguageList();
return (Language)(language_map.get(code.trim()));
} // end getLanguageForCode
/**
* Creates a <CODE>Locale</CODE> from a standard descriptor string.
*
* @param streq The string equivalent of the Locale to be created.
* @return The corresponding <CODE>Locale</CODE>, or the default <CODE>Locale</CODE> if the parameter is
* <CODE>null</CODE> or the empty string.
*/
public Locale createLocale(String streq)
{
if ((streq==null) || (streq.length()==0))
return Locale.getDefault(); // no locale
int p1 = streq.indexOf('_');
if (p1<0)
return new Locale(streq,""); // language but no country specified
String x_lang = streq.substring(0,p1);
int p2 = streq.indexOf('_',p1+1);
if (p2<0)
{ // there's only one underscore - figure out what part the last part is
String lastpart = streq.substring(p1+1);
if (lastpart.length()==2)
return new Locale(x_lang,lastpart); // language + country
else
return new Locale(x_lang,"",lastpart); // language + country(null) + variant
} // end if
// do all three variants
return new Locale(x_lang,streq.substring(p1+1,p2),streq.substring(p2+1));
} // end createLocale
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the singleton instance of the <CODE>International</CODE> object.
*
* @return The singleton instance of the <CODE>International</CODE> object.
*/
public static International get()
{
return self;
} // end get()
} // end class International

View File

@@ -0,0 +1,159 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
/**
* A utility class used by <CODE>International</CODE> that stores a language code and name pair.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
* @see International
*/
public final class Language implements Comparable
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private String m_code; // the language code
private String m_name; // the language name
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new <CODE>Language</CODE> object.
*
* @param code The language code.
* @param name The language name.
*/
Language(String code, String name)
{
m_code = code.trim();
m_name = name.trim();
} // end constructor
/*--------------------------------------------------------------------------------
* Overrides from class Object
*--------------------------------------------------------------------------------
*/
/**
* Indicates whether some other object is "equal to" this one.
*
* @param o The reference object with which to compare.
* @return <CODE>true</CODE> if this object is the same as the <CODE>o</CODE> argument; <CODE>false</CODE> otherwise.
*/
public boolean equals(Object o)
{
if ((o==null) || !(o instanceof Language))
return false;
if (this==(Language)o)
return true;
Language other = (Language)o;
return m_code.equals(other.m_code);
} // end equals
/**
* Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those
* provided by <CODE>java.util.Hashtable</CODE>.
*
* @return A hash code value for this object.
*/
public int hashCode()
{
return m_code.hashCode();
} // end hashCode
/**
* Returns a string representation of the object. In general, the <CODE>toString</CODE> method returns a string
* that "textually represents" this object.
*
* @return A string representation of the object.
*/
public String toString()
{
return m_name + " [" + m_code + "]";
} // end toString
/*--------------------------------------------------------------------------------
* Implementations from interface Comparable
*--------------------------------------------------------------------------------
*/
/**
* Compares this object with the specified object for order. Returns a negative integer, zero, or a positive
* integer as this object is less than, equal to, or greater than the specified object. <CODE>Language</CODE>
* objects are compared on their language name.
*
* @param o The Object to be compared.
* @return A negative integer, zero, or a positive integer as this object is less than, equal to, or greater than
* the specified object.
* @exception java.lang.ClassCastException If the specified object's type prevents it from being compared to
* this Object.
*/
public int compareTo(Object o)
{
if (o==null)
return 1;
if (o instanceof Language)
{ // compare country names
Language c = (Language)o;
return m_name.compareTo(c.m_name);
} // end if
return m_name.compareTo(o.toString());
} // end compareTo
/*--------------------------------------------------------------------------------
* External getters
*--------------------------------------------------------------------------------
*/
/**
* Returns the RFC 1766 language code for this language.
*
* @return The RFC 1766 language code for this language.
*/
public final String getCode()
{
return m_code;
} // end code
/**
* Returns the name of this language.
*
* @return The name of this language.
*/
public final String getName()
{
return m_name;
} // end name
} // end class Language

View File

@@ -0,0 +1,120 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.sql.*;
import org.apache.log4j.Logger;
/**
* A class containing miscellaneous public methods useful when working with MySQL databases. All
* public methods of {@link com.silverwrist.util.SQLUtils SQLUtils} are also accessible through this class.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class MySQLUtils extends SQLUtils
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(MySQLUtils.class);
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* MySQLUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>MySQLUtils.shutdown(statement);</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.
*/
public MySQLUtils()
{
super();
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Unlocks all database tables that were previously locked. Executes the MySQL statement "UNLOCK TABLES;".
*
* @param conn The connection on which one or more tables were previously locked.
*/
public static final void unlockTables(Connection conn)
{
Statement stmt = null;
try
{ // do the update
stmt = conn.createStatement();
stmt.executeUpdate("UNLOCK TABLES;");
} // end try
catch (SQLException e)
{ // warn if there was an error here
logger.warn("DB error in unlockTables()",e);
} // end catch
finally
{ // shutdown the statement before we go
shutdown(stmt);
} // end finally
} // end unlockTables
/**
* Gets the ID of the most recent insert made to a table with an AUTO_INCREMENT column. This assumes that the
* column is of integer type. Executes the MySQL statement "SELECT LAST_INSERT_ID();" and returns the value
* that that statement returns.
*
* @param conn Database connection on which to perform the operation.
* @return The value of the last inserted ID on this connection.
* @exception java.sql.SQLException If an error occurred in the execution, or if the SELECT statement returned
* no rows (which it should not do).
*/
public static final int getLastInsertInt(Connection conn) throws SQLException
{
Statement stmt = null;
ResultSet rs = null;
try
{ // perform the operation
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT LAST_INSERT_ID();");
if (!(rs.next()))
throw new SQLException("internal error - getLastInsertInt SELECT should have returned OK");
return rs.getInt(1);
} // end try
finally
{ // shut down the objects before we go
shutdown(rs);
shutdown(stmt);
} // end finally
} // end getLastInsertInt
} // end class MySQLUtils

View File

@@ -0,0 +1,424 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2001-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.util.BitSet;
/**
* A variant of the <CODE>BitSet</CODE> that can express itself as a character string. Each
* character in the resulting string represents a flag that is "set." Up to 91 flags can be
* specified per <CODE>OptionSet</CODE>.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
* @see java.util.BitSet
*/
public class OptionSet extends BitSet
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
// The alphabet to use to store individual flags.
private static final String ALPHA = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
+ "!#$%&()*+,-./:;<=>?@[]^_`{|}~";
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
/**
* Creates a new <CODE>OptionSet</CODE>. All bits are initially <CODE>false</CODE>.
*/
public OptionSet()
{
super();
} // end constructor
/**
* Creates an <CODE>OptionSet</CODE> whose initial size is large enough to explicitly represent bits with
* indices in the range 0 through nbits-1. All bits are initially <CODE>false</CODE>. The maximum
* size of the <CODE>OptionSet</CODE> is 91.
*
* @param nbits The initial size of the bit set.
* @exception java.lang.NegativeArraySizeException If the specified initial size is negative.
*/
public OptionSet(int nbits)
{
super(Math.min(nbits,ALPHA.length()));
} // end constructor
/**
* Creates an <CODE>OptionSet</CODE> from an array of characters representing "set" options.
*
* @param options The options to be set in the new <CODE>OptionSet</CODE>.
*/
public OptionSet(char[] options)
{
super(); // initialize all bits to 0
for (int i=0; i<options.length; i++)
{ // look at all the chars in the option string and set bits accordingly
int ndx = ALPHA.indexOf(options[i]);
if (ndx>=0)
super.set(ndx);
} // end for
} // end constructor
/**
* Creates an <CODE>OptionSet</CODE> from a string of characters representing "set" options.
*
* @param options The options to be set in the new <CODE>OptionSet</CODE>.
*/
public OptionSet(String options)
{
this(options.toCharArray());
} // end constructor
/*--------------------------------------------------------------------------------
* Internal functions
*--------------------------------------------------------------------------------
*/
/**
* Returns a <CODE>StringBuffer</CODE> representing the current state of this <CODE>OptionSet</CODE>,
* with one character in it for each bit that is set.
*
* @return A <CODE>StringBuffer</CODE> containing the current state of the <CODE>OptionSet</CODE>.
*/
private StringBuffer asStringBuffer()
{
StringBuffer b = new StringBuffer();
for (int i=0; i<super.length(); i++)
if (super.get(i))
b.append(ALPHA.charAt(i));
return b;
} // end asStringBuffer
/*--------------------------------------------------------------------------------
* Overrides from class BitSet
*--------------------------------------------------------------------------------
*/
/**
* Sets the bit specified by the index to <CODE>false</CODE>.
*
* @param bitIndex The index of the bit to be cleared.
* @exception java.lang.IndexOutOfBoundsException If the specified index is negative or greater than the
* maximum option for an <CODE>OptionSet</CODE>.
*/
public void clear(int bitIndex)
{
if (bitIndex>=ALPHA.length())
throw new IndexOutOfBoundsException();
super.clear(bitIndex);
} // end clear
/**
* Sets the bits from the specified <CODE>fromIndex</CODE> (inclusive) to the specified <CODE>toIndex</CODE>
* (exclusive) to <CODE>false</CODE>.
*
* @param fromIndex Index of the first bit to be cleared.
* @param toIndex Index after the last bit to be cleared.
* @exception java.lang.IndexOutOfBoundException If <CODE>fromIndex</CODE> is negative, or <CODE>fromIndex</CODE>
* is greater than the maximum option for an <CODE>OptionSet</CODE>, or <CODE>toIndex</CODE> is negative,
* or <CODE>toIndex</CODE> is greater than the maximum option for an <CODE>OptionSet</CODE>, or
* <CODE>fromIndex</CODE> is larger than <CODE>toIndex</CODE>.
*/
public void clear(int fromIndex, int toIndex)
{
if ((fromIndex>=ALPHA.length()) || (toIndex>ALPHA.length()))
throw new IndexOutOfBoundsException();
super.clear(fromIndex,toIndex);
} // end clear
/**
* Cloning this <CODE>OptionSet</CODE> produces a new <CODE>OptionSet</CODE> that is equal to it. The clone of the
* option set is another option set that has exactly the same bits set to true as this option set and the same
* current size.
*
* @return A clone of this option set.
*/
public Object clone()
{
OptionSet rc = new OptionSet(this.size());
for (int i=this.nextSetBit(0); i>=0; i=this.nextSetBit(i+1))
rc.set(i);
return rc;
} // end clone
/**
* Sets the bit at the specified index to to the complement of its current value.
*
* @param bitIndex The index of the bit to flip.
* @exception java.lang.IndexOutOfBoundsException If the specified index is negative or greater than the
* maximum option for an <CODE>OptionSet</CODE>.
*/
public void flip(int bitIndex)
{
if (bitIndex>=ALPHA.length())
throw new IndexOutOfBoundsException();
super.flip(bitIndex);
} // end flip
/**
* Sets the bits from the specified <CODE>fromIndex</CODE> (inclusive) to the specified <CODE>toIndex</CODE>
* (exclusive) to the complement of their current values.
*
* @param fromIndex Index of the first bit to be flipped.
* @param toIndex Index after the last bit to be flipped.
* @exception java.lang.IndexOutOfBoundException If <CODE>fromIndex</CODE> is negative, or <CODE>fromIndex</CODE>
* is greater than the maximum option for an <CODE>OptionSet</CODE>, or <CODE>toIndex</CODE> is negative,
* or <CODE>toIndex</CODE> is greater than the maximum option for an <CODE>OptionSet</CODE>, or
* <CODE>fromIndex</CODE> is larger than <CODE>toIndex</CODE>.
*/
public void flip(int fromIndex, int toIndex)
{
if ((fromIndex>=ALPHA.length()) || (toIndex>ALPHA.length()))
throw new IndexOutOfBoundsException();
super.flip(fromIndex,toIndex);
} // end flip
/**
* Returns the value of the bit with the specified index. The value is <CODE>true</CODE> if the bit with
* the index <CODE>bitIndex</CODE> is currently set in this <CODE>OptionSet</CODE>; otherwise, the result
* is <CODE>false</CODE>.
*
* @param bitIndex The bit index.
* @return The value of the bit with the specified index.
* @exception java.lang.IndexOutOfBoundsException If the specified index is negative or greater than the
* maximum option for an <CODE>OptionSet</CODE>.
*/
public boolean get(int bitIndex)
{
if (bitIndex>=ALPHA.length())
throw new IndexOutOfBoundsException();
return super.get(bitIndex);
} // end get
/**
* Returns a new <CODE>OptionSet</CODE> composed of bits from this <CODE>OptionSet</CODE> from
* <CODE>fromIndex</CODE> (inclusive) to <CODE>toIndex</CODE> (exclusive).
*
* @param fromIndex Index of the first bit to be included.
* @param toIndex Index after the last bit to be included.
* @return A new <CODE>OptionSet</CODE> from a range of this <CODE>OptionSet</CODE>.
* @exception java.lang.IndexOutOfBoundException If <CODE>fromIndex</CODE> is negative, or <CODE>fromIndex</CODE>
* is greater than the maximum option for an <CODE>OptionSet</CODE>, or <CODE>toIndex</CODE> is negative,
* or <CODE>toIndex</CODE> is greater than the maximum option for an <CODE>OptionSet</CODE>, or
* <CODE>fromIndex</CODE> is larger than <CODE>toIndex</CODE>.
*/
public BitSet get(int fromIndex, int toIndex)
{
if ((fromIndex>=ALPHA.length()) || (toIndex>ALPHA.length()))
throw new IndexOutOfBoundsException();
BitSet tmp = super.get(fromIndex,toIndex);
OptionSet rc = new OptionSet(tmp.size());
for (int i=tmp.nextSetBit(0); i>=0; i=tmp.nextSetBit(i+1))
rc.set(i);
return rc;
} // end get
/**
* Sets the bit specified by the index to <CODE>true</CODE>.
*
* @param bitIndex The index of the bit to be set.
* @exception java.lang.IndexOutOfBoundsException If the specified index is negative or greater than the
* maximum option for an <CODE>OptionSet</CODE>.
*/
public void set(int bitIndex)
{
if (bitIndex>=ALPHA.length())
throw new IndexOutOfBoundsException();
super.set(bitIndex);
} // end set
/**
* Sets the bit specified by the index to the specified value.
*
* @param bitIndex The index of the bit to be set.
* @param value A boolean value to set.
* @exception java.lang.IndexOutOfBoundsException If the specified index is negative or greater than the
* maximum option for an <CODE>OptionSet</CODE>.
*/
public void set(int bitIndex, boolean value)
{
if (bitIndex>=ALPHA.length())
throw new IndexOutOfBoundsException();
super.set(bitIndex,value);
} // end set
/**
* Sets the bits from the specified <CODE>fromIndex</CODE> (inclusive) to the specified <CODE>toIndex</CODE>
* (exclusive) to <CODE>true</CODE>.
*
* @param fromIndex Index of the first bit to be set.
* @param toIndex Index after the last bit to be set.
* @exception java.lang.IndexOutOfBoundException If <CODE>fromIndex</CODE> is negative, or <CODE>fromIndex</CODE>
* is greater than the maximum option for an <CODE>OptionSet</CODE>, or <CODE>toIndex</CODE> is negative,
* or <CODE>toIndex</CODE> is greater than the maximum option for an <CODE>OptionSet</CODE>, or
* <CODE>fromIndex</CODE> is larger than <CODE>toIndex</CODE>.
*/
public void set(int fromIndex, int toIndex)
{
if ((fromIndex>=ALPHA.length()) || (toIndex>ALPHA.length()))
throw new IndexOutOfBoundsException();
super.set(fromIndex,toIndex);
} // end set
/**
* Sets the bits from the specified <CODE>fromIndex</CODE> (inclusive) to the specified <CODE>toIndex</CODE>
* (exclusive) to the specified value.
*
* @param fromIndex Index of the first bit to be set.
* @param toIndex Index after the last bit to be set.
* @param value A boolean value to set.
* @exception java.lang.IndexOutOfBoundException If <CODE>fromIndex</CODE> is negative, or <CODE>fromIndex</CODE>
* is greater than the maximum option for an <CODE>OptionSet</CODE>, or <CODE>toIndex</CODE> is negative,
* or <CODE>toIndex</CODE> is greater than the maximum option for an <CODE>OptionSet</CODE>, or
* <CODE>fromIndex</CODE> is larger than <CODE>toIndex</CODE>.
*/
public void set(int fromIndex, int toIndex, boolean value)
{
if ((fromIndex>=ALPHA.length()) || (toIndex>ALPHA.length()))
throw new IndexOutOfBoundsException();
super.set(fromIndex,toIndex,value);
} // end set
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Sets the value of the specified bit in the <CODE>OptionSet</CODE> to a specified Boolean
* value, and returns an indication of whether that value was changed.
*
* @param ndx The index of the bit to be assigned.
* @param val <CODE>true</CODE> to set the corresponding bit, <CODE>false</CODE> to clear it.
* @return <CODE>true</CODE> if the value of the bit in the <CODE>OptionSet</CODE> was changed by this
* operation, <CODE>false</CODE> if not.
* @exception java.lang.IndexOutOfBoundsException If the specified index is negative or greater than the
* maximum option for an <CODE>OptionSet</CODE>.
*/
public boolean assign(int ndx, boolean val)
{
if (ndx>=ALPHA.length())
throw new IndexOutOfBoundsException();
boolean old = super.get(ndx);
super.set(ndx,val);
return (old!=val);
} // end assign
/**
* Resets the state of this <CODE>OptionSet</CODE> from an array of characters representing "set" options.
*
* @param options The options to be set in the new <CODE>OptionSet</CODE>. All options not specified will
* be cleared.
*/
public void assign(char[] options)
{
super.clear();
for (int i=0; i<options.length; i++)
{ // look at all the chars in the option string and set bits accordingly
int ndx = ALPHA.indexOf(options[i]);
if (ndx>=0)
super.set(ndx);
} // end for
} // end assign
/**
* Resets the state of this <CODE>OptionSet</CODE> from a string of characters representing "set" options.
*
* @param options The options to be set in the new <CODE>OptionSet</CODE>. All options not specified will
* be cleared.
*/
public void assign(String options)
{
if (options!=null)
assign(options.toCharArray());
} // end assign
/**
* Returns a character array representing the current state of this <CODE>OptionSet</CODE>,
* with one character in it for each bit that is set.
*
* @return A character array containing the current state of the <CODE>OptionSet</CODE>.
*/
public char[] asCharArray()
{
return asStringBuffer().toString().toCharArray();
} // end asCharArray
/**
* Returns a string representing the current state of this <CODE>OptionSet</CODE>,
* with one character in it for each bit that is set.
*
* @return A string containing the current state of the <CODE>OptionSet</CODE>.
*/
public String asString()
{
return asStringBuffer().toString();
} // end asString
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the character associated with a specific "option index" by all <CODE>OptionSet</CODE> instances.
*
* @param index The index of the character to retrieve.
* @return The character associated with that index.
* @exception java.lang.IndexOutOfBoundsException If the specified index is out of range.
*/
public static final char getOptionChar(int index)
{
if ((index<0) || (index>=ALPHA.length()))
throw new IndexOutOfBoundsException();
return ALPHA.charAt(index);
} // end getOptionChar
} // end class OptionSet

View File

@@ -0,0 +1,127 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.sql.*;
/**
* A class containing miscellaneous public methods useful when working with SQL databases.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class SQLUtils
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* SQLUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>SQLUtils.shutdown(statement);</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.
*/
public SQLUtils()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Closes a <CODE>ResultSet</CODE> cleanly, without throwing an exception.
*
* @param rs The <CODE>ResultSet</CODE> to be closed.
* @see java.sql.ResultSet#close()
*/
public static final void shutdown(ResultSet rs)
{
try
{ // close the ResultSet
if (rs!=null)
rs.close();
} // end try
catch (SQLException e)
{ // ignore any SQL errors
} // end catch
} // end shutdown
/**
* Closes a <CODE>Statement</CODE> cleanly, without throwing an exception.
*
* @param rs The <CODE>Statement</CODE> to be closed.
* @see java.sql.Statement#close()
*/
public static final void shutdown(Statement stmt)
{
try
{ // close the Statement
if (stmt!=null)
stmt.close();
} // end try
catch (SQLException e)
{ // ignore any SQL errors
} // end catch
} // end shutdown
/**
* Closes a <CODE>Connection</CODE> cleanly, without throwing an exception.
*
* @param rs The <CODE>Connection</CODE> to be closed.
* @see java.sql.Connection#close()
*/
public static final void shutdown(Connection conn)
{
try
{ // close the Connection
if (conn!=null)
conn.close();
} // end try
catch (SQLException e)
{ // ignore any SQL errors
} // end catch
} // end shutdown
/**
* Fetches the return count from a query such as "SELECT COUNT(*) FROM ...". All such queries will always
* return at least one row, with the count.
*
* @param rs The <CODE>ResultSet</CODE> returned from the query execution.
* @param column The column index in which the return value may be found.
* @return The value of that column (usually, the count you were querying for).
* @exception java.sql.SQLException If there was no returned row, or there was a data type mismatch on the column.
*/
public static final int getReturnCountInt(ResultSet rs, int column) throws SQLException
{
if (!(rs.next()))
throw new SQLException("expected return count row, not present");
return rs.getInt(column);
} // end getReturnCountInt
} // end class SQLUtils

View File

@@ -0,0 +1,349 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;
import org.apache.log4j.Logger;
/**
* Common string utilities. Inherits from the <CODE>org.apache.commons.lang.StringUtils</CODE>
* class, so it contains everything that contains.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class StringUtils extends org.apache.commons.lang.StringUtils
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(StringUtils.class);
private static final char[] HTML_ENCODE_CHARS = { '"', '&', '<', '>' };
private static final String VAR_START = "${";
private static final String VAR_END = "}";
private static final Set TRUE_STRINGS;
private static final Set FALSE_STRINGS;
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* StringUtils instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>StringUtils.trim(" foo ");</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.
*/
public StringUtils()
{
super();
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Performs HTML encoding of an arbitrary string. When a string is HTML encoded, the double-quote (&quot;),
* ampersand (&amp;), less-than (&lt;), and greater-than (&gt;) characters are transformed to their HTML
* entity equivalents; all other characters are left untouched.
*
* @param str The string to be HTML-encoded. May be <B><CODE>null</CODE></B>.
* @return The HTML-encoded equivalent of <CODE>str</CODE>. If <CODE>str</CODE> is
* <B><CODE>null</CODE></B>, returns <B><CODE>null</CODE></B>.
*/
public static final String encodeHTML(String str)
{
if (str==null)
return null; // safety feature
AnyCharMatcher nhc = new AnyCharMatcher(HTML_ENCODE_CHARS);
int ndx = nhc.get(str);
if (ndx<0)
return str; // trivial short-circuit case
StringBuffer buf = new StringBuffer();
while (ndx>=0)
{ // append the matched "head" and then the encoded character
if (ndx>0)
buf.append(str.substring(0,ndx));
switch (str.charAt(ndx++))
{
case '"':
buf.append("&quot;");
break;
case '&':
buf.append("&amp;");
break;
case '<':
buf.append("&lt;");
break;
case '>':
buf.append("&gt;");
break;
} // end switch
if (ndx==str.length())
return buf.toString(); // munched the entire string - all done!
str = str.substring(ndx);
ndx = nhc.get(str);
} // end while
buf.append(str); // append the unmatched tail
return buf.toString();
} // end encodeHTML
/**
* Translates a string into <CODE>application/x-www-form-urlencoded</CODE> format, using a UTF-8 encoding.
*
* @param s The string to be encoded. May be <CODE>null</CODE>.
* @return The translated string value, or <CODE>null</CODE> if <CODE>null</CODE> was passed in.
*/
public static final String encodeURL(String s)
{
try
{ // the old URLEncoder.encode(str) method is deprecated as of JDK1.4, use the new one
return ((s==null) ? null : URLEncoder.encode(s,"UTF-8"));
} // end try
catch (UnsupportedEncodingException e)
{ // this should never happen, but we gotta catch it anyway
logger.fatal("WTF? encodeURL doesn't support UTF-8? You're crazy!");
return null;
} // end catch
} // end encodeURL
/**
* Returns <CODE>true</CODE> if the given string is a representation of a Boolean <CODE>true</CODE> value.
* Values that represent a valid Boolean <CODE>true</CODE> value include "true", "yes", "on", and "1".
*
* @param test The string to be tested.
* @return <CODE>true</CODE> if the string represents a Boolean <CODE>true</CODE> value, <CODE>false</CODE> if not.
*/
public static final boolean isBooleanTrue(String test)
{
if (test==null)
return false;
return TRUE_STRINGS.contains(test.trim().toLowerCase());
} // end isBooleanTrue
/**
* Returns <CODE>true</CODE> if the given string is a representation of a Boolean <CODE>false</CODE> value.
* Values that represent a valid Boolean <CODE>false</CODE> value include "false", "no", "off", and "0".
*
* @param test The string to be tested.
* @return <CODE>true</CODE> if the string represents a Boolean <CODE>false</CODE> value, <CODE>false</CODE> if not.
*/
public static final boolean isBooleanFalse(String test)
{
if (test==null)
return false;
return FALSE_STRINGS.contains(test.trim().toLowerCase());
} // end isBooleanTrue
/**
* Replaces variable substitutions in a string. Variable substitutions are strings of the form
* <CODE>${<EM>varname</EM>}</CODE>. The <EM>varname</EM> names are looked up in the supplied
* <CODE>Map</CODE>, and the values of variables in that map are substituted.<P>
* Only variable names that exist in the <CODE>Map</CODE> are replaced; other variable strings
* in the supplied string are left untouched. Variable substitution values may themselves contain
* variables; those variables are recursively replaced. (<B><EM>Caution:</EM></B> The code cannot
* detect variable substitutions that contain themselves, or two variables that contain each other.
* Avoid these situations.)
*
* @param base The string to be operated on. If this parameter is <CODE>null</CODE>, the
* method will return <CODE>null</CODE>.
* @param vars The mapping of variable name to value substitutions. If this parameter is
* <CODE>null</CODE> or an empty map, no substitutions will be performed on
* <CODE>base</CODE>.
* @return The <CODE>base</CODE> string with all variable substitutions made as detailed above.
*/
public static final String replaceAllVariables(String base, Map vars)
{
if ((base==null) || (vars==null) || vars.isEmpty())
return base; // safety feature
String work = base;
boolean did_replace = false;
boolean retest = true;
do
{ // main loop for replacing all variables
did_replace = false;
Iterator it = vars.keySet().iterator();
while (it.hasNext())
{ // variable start is there...
if (retest)
{ // only perform this test on the first iteration and after we know we've replaced a variable
if (work.indexOf(VAR_START)<0)
return work; // no more variables in text - all done!
retest = false;
} // end if
// get variable name and see if it's present
String vname = it.next().toString();
String var_full = VAR_START + vname + VAR_END;
if (work.indexOf(var_full)>=0)
{ // OK, this variable is in place
work = replace(work,var_full,vars.get(vname).toString());
did_replace = true;
retest = true;
} // end if
} // end while
} while (did_replace); // end do
return work; // all done!
} // end replaceAllVariables
/**
* Splits the provided text into a list, based on a given separator. The separator is not included in the
* returned String list. The maximum number of splits to perfom can be controlled.
*
* @param text The string to parse.
* @param separator Character used as the delimiter.
* @param limit The maximum number of elements to include in the list. A zero or negative value implies no limit.
* @return A list of parsed Strings.
*/
public static final List split1List(String text, char separator, int limit)
{
if (text==null)
return Collections.EMPTY_LIST;
if (limit<=0)
limit = Integer.MAX_VALUE;
ArrayList rc = new ArrayList();
String work = text;
int p = work.indexOf(separator);
while ((work.length()>0) && (p>=0) && (--limit>0))
{ // add elements to the ArrayList
if (p==0)
rc.add("");
else
rc.add(work.substring(0,p));
work = work.substring(p+1);
p = work.indexOf(separator);
} // end while
rc.add(work);
rc.trimToSize();
return rc;
} // end split1list
/**
* Splits the provided text into a list, based on a given separator. The separator is not included in the
* returned String list.
*
* @param text The string to parse.
* @param separator Character used as the delimiter.
* @return A list of parsed Strings.
*/
public static final List split1List(String text, char separator)
{
return split1List(text,separator,0);
} // end split1list
/**
* Splits the provided text into a list, based on a given separator. The separator is not included in the
* returned String array. The maximum number of splits to perfom can be controlled.
*
* @param text The string to parse.
* @param separator Character used as the delimiter.
* @param limit The maximum number of elements to include in the list. A zero or negative value implies no limit.
* @return An array of parsed Strings.
*/
public static final String[] split1(String text, char separator, int limit)
{
List tmp = split1List(text,separator,limit);
String[] rc = new String[tmp.size()];
tmp.toArray(rc);
return rc;
} // end split1
/**
* Splits the provided text into a list, based on a given separator. The separator is not included in the
* returned String array.
*
* @param text The string to parse.
* @param separator Character used as the delimiter.
* @return An array of parsed Strings.
*/
public static final String[] split1(String text, char separator)
{
return split1(text,separator,0);
} // end split1
/*--------------------------------------------------------------------------------
* Static initializer
*--------------------------------------------------------------------------------
*/
static
{ // get the boolean values resource
ResourceBundle bv = ResourceBundle.getBundle("com.silverwrist.util.BooleanValues");
// Load the Boolean "true" values.
String[] values = split(bv.getString("values.true"),"|");
HashSet tmp = new HashSet();
for (int i=0; i<values.length; i++)
tmp.add(values[i].toLowerCase());
tmp.add("1"); // always add the default English values, too
tmp.add("true");
tmp.add("yes");
tmp.add("on");
TRUE_STRINGS = Collections.unmodifiableSet(tmp);
// Load the Boolean "false" values.
values = split(bv.getString("values.false"),"|");
tmp = new HashSet();
for (int i=0; i<values.length; i++)
tmp.add(values[i].toLowerCase());
tmp.add("0"); // always add the default English values, too
tmp.add("false");
tmp.add("no");
tmp.add("off");
FALSE_STRINGS = Collections.unmodifiableSet(tmp);
} // end static initializer
} // end class StringUtils

View File

@@ -0,0 +1,261 @@
# The contents of this file are subject to the Mozilla Public License Version 1.1
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
#
# Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
# WARRANTY OF ANY KIND, either express or implied. See the License for the specific
# language governing rights and limitations under the License.
#
# The Original Code is the Venice Web Communities System.
#
# The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
# for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
# Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# -------------------------------------------------------------------------------------
# This list of countries is taken from the ISO 3166 standard list of country names and
# 2-letter codes <http://www.din.de/gremien/nas/nabd/iso3166ma/>. When adding new
# entries to this file, make sure and add it in sorted order by country NAME! You can
# re-sort the country entries with "sort -t = -k 2 input > output", but then make sure
# the "XX=(unknown)" entry appears first!
XX=(unknown)
AF=Afghanistan
AL=Albania
DZ=Algeria
AS=American Samoa
AD=Andorra
AO=Angola
AI=Anguilla
AQ=Antarctica
AG=Antigua and Barbuda
AR=Argentina
AM=Armenia
AW=Aruba
AU=Australia
AT=Austria
AZ=Azerbaijan
BS=Bahamas
BH=Bahrain
BD=Bangladesh
BB=Barbados
BY=Belarus
BE=Belgium
BZ=Belize
BJ=Benin
BM=Bermuda
BT=Bhutan
BO=Bolivia
BA=Bosnia and Herzegovina
BW=Botswana
BV=Bouvet Island
BR=Brazil
IO=British Indian Ocean Territory
BN=Brunei Darussalam
BG=Bulgaria
BF=Burkina Faso
BI=Burundi
KH=Cambodia
CM=Cameroon
CA=Canada
CV=Cape Verde
KY=Cayman Islands
CF=Central African Republic
TD=Chad
CL=Chile
CN=China
CX=Chrismas Island
CC=Cocos (Keeling) Islands
CO=Colombia
KM=Comoros
CG=Congo
CD=Congo (Democratic Republic of)
CK=Cook Islands
CR=Costa Rica
CI=Cote D''Ivoire
HR=Croatia
CU=Cuba
CY=Cyprus
CZ=Czech Republic
DK=Denmark
DJ=Djibouti
DM=Dominica
DO=Dominican Republic
TP=East Timor
EC=Ecuador
EG=Egypt
SV=El Salvador
GQ=Equatorial Guinea
ER=Eritrea
EE=Estonia
ET=Ethiopia
FK=Falkland Islands (Malvinas)
FO=Faroe Islands
FJ=Fiji
FI=Finland
FR=France
GF=French Guiana
PF=French Polynesia
TF=French Southern Territories
GA=Gabon
GM=Gambia
GE=Georgia
DE=Germany
GH=Ghana
GI=Gibraltar
GR=Greece
GL=Greenland
GD=Grenada
GP=Guadeloupe
GU=Guam
GT=Guatemala
GN=Guinea
GW=Guinea-Bissau
GY=Guyana
HT=Haiti
HM=Heard Island and McDonald Islands
VA=Holy See (Vatican City State)
HN=Honduras
HK=Hong Kong
HU=Hungary
IS=Iceland
IN=India
ID=Indonesia
IR=Iran (Islamic Republic of)
IQ=Iraq
IE=Ireland
IL=Israel
IT=Italy
JM=Jamaica
JP=Japan
JO=Jordan
KZ=Kazakhstan
KE=Kenya
KI=Kiribati
KP=Korea (Democratic People's Republic of)
KR=Korea (Republic of)
KW=Kuwait
KG=Kyrgyzstan
LA=Lao People's Democratic Republic
LV=Latvia
LB=Lebanon
LS=Lesotho
LR=Liberia
LY=Libyan Arab Jamahirya
LI=Liechtenstein
LT=Lithuania
LU=Luxembourg
MO=Macau
MK=Macedonia (Former Yugoslav Republic of)
MG=Madagascar
MW=Malawi
MY=Malaysia
MV=Maldives
ML=Mali
MT=Malta
MH=Marshall Islands
MQ=Martinique
MR=Mauritania
MU=Mauritius
YT=Mayotte
MX=Mexico
FM=Micronesia (Federated States of)
MD=Moldova, Republic of
MC=Monaco
MN=Mongolia
MS=Montserrat
MA=Morocco
MZ=Mozambique
MM=Myanmar
NA=Namibia
NR=Nauru
NP=Nepal
NL=Netherlands
AN=Netherlands Antillies
NC=New Caledonia
NZ=New Zealand
NI=Nicaragua
NE=Niger
NG=Nigeria
NU=Niue
NF=Norfolk Island
MP=Northern Mariana Islands'),
NO=Norway
OM=Oman
PK=Pakistan
PW=Palau
PS=Palestinian Territory, Occupied
PA=Panama
PG=Papua New Guinea
PY=Paraguay
PE=Peru
PH=Phillipines
PN=Pitcairn
PL=Poland
PT=Portugal
PR=Puerto Rico
QA=Qatar
RE=Reunion
RO=Romania
RU=Russian Federation
RW=Rwanda
SH=Saint Helena
KN=Saint Kitts and Nevis
LC=Saint Lucia
PM=Saint Pierre and Miquelon
VC=Saint Vincent and The Grenadines
WS=Samoa
SM=San Marino
ST=Sao Tome and Principe
SA=Saudi Arabia
SN=Senegal
SC=Seychelles
SL=Sierra Leone
SG=Singapore
SK=Slovakia
SI=Slovenia
SB=Solomon Islands
SO=Somalia
ZA=South Africa
GS=South Georgia and the South Sandwich Islands
ES=Spain
LK=Sri Lanka
SD=Sudan
SR=Suriname
SJ=Svalbard and Jan Mayen
SZ=Swaziland
SE=Sweden
CH=Switzerland
SY=Syrian Arab Republic
TW=Taiwan (Province of China)
TJ=Tajikistan
TZ=Tanzania, United Republic of
TH=Thailand
TG=Togo
TK=Tokelau
TO=Tonga
TT=Trinidad and Tobago
TN=Tunisia
TR=Turkey
TM=Turkmenistan
TC=Turks and Caicos Islands
TV=Tuvalu
UG=Uganda
UA=Ukraine
AE=United Arab Emirates
GB=United Kingdom
US=United States
UM=United States Minor Outlying Islands
UY=Uruguay
UZ=Uzbekistan
VU=Vanatu
VE=Venezuela
VN=Viet Nam
VG=Virgin Islands (British)
VI=Virgin Islands (U.S.)
WF=Wallis and Futuna
EH=Western Sahara
YE=Yemen
YU=Yugoslavia
ZM=Zambia
ZW=Zimbabwe

View File

@@ -0,0 +1,272 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util.image;
import java.awt.RenderingHints;
import java.awt.image.*;
import java.awt.image.renderable.ParameterBlock;
import java.io.*;
import java.util.*;
import javax.imageio.*;
import javax.imageio.stream.*;
import javax.media.jai.*;
/**
* A class that performs "normalization" on an image to fit within a bounding box of a specified pixel
* size. "Normalized" images are scaled down proportionally to fit the bounding box, then centered over
* a black backdrop (so the image will be "letterboxed" if it has a larger H:V aspect ratio than the bounding
* box, or "pillarboxed" if it has a smaller H:V aspect ratio than the bounding box).
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class ImageNormalizer
{
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* ImageNormalizer instances should NOT be constructed in standard programming.
* Instead, the class should be used as <code>ImageNormalizer.normalizeImage(...);</code>.
* This constructor is public to permit tools that require a JavaBean instance
* to operate.
*/
public ImageNormalizer()
{
super();
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* "Normalizes" an image to fit within a bounding box of a specified pixel size. "Normalized" images are
* scaled down proportionally to fit the bounding box, then centered over a black backdrop (so the image
* will be "letterboxed" if it has a larger H:V aspect ratio than the bounding box, or "pillarboxed" if it
* has a smaller H:V aspect ratio than the bounding box).
*
* @param image_data Raw image data from the input, in any ImageIO-recognized format.
* @param width The width of the bounding box to use to normalize the image.
* @param height The height of the bounding box to use to normalize the image.
* @param output_type The desired MIME type for output (such as "image/jpeg").
* @return The normalized image data as a byte array.
* @exception com.silverwrist.util.image.ImageNormalizerException An error occurred in the image data or
* the image transformation process.
* @see ImageNormalizerException
*/
public static byte[] normalizeImage(InputStream image_data, int width, int height, String output_type)
throws ImageNormalizerException
{
PlanarImage img1; // initial image
try
{ // get an image input stream for the image
ImageInputStream iistm = ImageIO.createImageInputStream(image_data);
// create the "ImageRead" operation to load the image; it will autodetect the
// image format and create an appropriate ImageReader
ParameterBlock pb = new ParameterBlock();
pb.add(iistm);
pb.add(new Integer(0));
pb.add(Boolean.FALSE);
pb.add(Boolean.FALSE);
RenderedOp rop = JAI.create("ImageRead",pb);
img1 = rop.getRendering();
} // end try
catch (IOException e)
{ // try to create the ImageInputStream
throw new ImageNormalizerException("Unable to load image",e);
} // end catch
catch (RuntimeException re)
{ // unable to get the rendering here!
throw new ImageNormalizerException("Image data not a valid image format",re);
} // end catch
try
{ // Compute the scaling factors required to get the image down to the appropriate size, then choose
// the smaller of the two to use as the final scaling factor. Note that we always scale DOWN,
// not UP.
Float scale_width = null, scale_height = null;
if (img1.getWidth()>width)
scale_width = new Float((float)width / (float)(img1.getWidth()));
if (img1.getHeight()>height)
scale_height = new Float((float)height / (float)(img1.getHeight()));
Float scale = null;
if (scale_width!=null)
{ // we can scale by width, how about height?
if (scale_height!=null)
{ // yes, height too...pick the smaller of the two
if (scale_width.floatValue()<scale_height.floatValue())
scale = scale_width;
else
scale = scale_height;
} // end if
else // no, just width
scale = scale_width;
} // end if
else if (scale_height!=null) // can only scale by height
scale = scale_height;
// If we need to scale the image now, do so.
PlanarImage img2; // image post-scaling
if (scale!=null)
{ // scale the image down!
ParameterBlock pb1 = new ParameterBlock();
pb1.addSource(img1);
pb1.add(scale.floatValue());
pb1.add(scale.floatValue());
pb1.add(0.0F);
pb1.add(0.0F);
pb1.add(Interpolation.getInstance(Interpolation.INTERP_BILINEAR));
img2 = JAI.create("scale",pb1);
} // end if
else // just use this as the next image
img2 = img1;
// Figure out the offsets required to center the new image within the "frame."
int offset_x = (width - img2.getWidth()) / 2;
int offset_y = (height - img2.getHeight()) / 2;
// If we need to translate the image now, do so.
PlanarImage img3; // image after scaling and translation
if ((offset_x!=0) || (offset_y!=0))
{ // set up a translation to move the image to the right location
ParameterBlock pb2 = new ParameterBlock();
pb2.addSource(img2);
pb2.add((float)offset_x);
pb2.add((float)offset_y);
pb2.add(Interpolation.getInstance(Interpolation.INTERP_NEAREST));
img3 = JAI.create("translate",pb2);
} // end if
else // just take the image as it is
img3 = img2;
// To set up the backdrop, first we need to create an image of the right size but with the same
// sample model and color model as our transformed image.
TiledImage back1 = new TiledImage(0,0,width,height,0,0,img3.getSampleModel(),img3.getColorModel());
// Now we need to make that image black. The easiest way to do that is multiply all pixel
// values in the image by 0.
ParameterBlock pb = new ParameterBlock();
pb.addSource(back1);
double[] parms = new double[1];
parms[0] = 0.0;
pb.add(parms);
PlanarImage back2 = JAI.create("multiplyconst",pb);
// Now overlay the scaled/translated image on top of the background to get the final image.
PlanarImage final_img = JAI.create("overlay",back2,img3);
// Now we need to output this new image in the right format.
ByteArrayOutputStream stm = new ByteArrayOutputStream();
ImageOutputStream iostm = ImageIO.createImageOutputStream(stm);
// Get an ImageWriter for the MIME type.
Iterator it = ImageIO.getImageWritersByMIMEType(output_type);
ImageWriter iwr = (ImageWriter)(it.next());
// Create the ParameterBlock and the operation. Most of the parameters are null, but we
// do need to specify the ImageWriter right at the end.
pb = new ParameterBlock();
pb.addSource(final_img);
pb.add(iostm);
pb.add(null);
pb.add(Boolean.FALSE);
pb.add(Boolean.FALSE);
pb.add(Boolean.TRUE);
pb.add(Boolean.FALSE);
pb.add(null);
pb.add(null);
pb.add(null);
pb.add(null);
pb.add(null);
pb.add(null);
pb.add(null);
pb.add(iwr);
RenderedOp rop = JAI.create("ImageWrite",pb);
rop.getSourceImage(0).removeSink(rop); // disconnect the image modification mechanism
// Return the new image data.
iostm.flush();
return stm.toByteArray();
} // end try
catch (Exception e)
{ // catchall exception
throw new ImageNormalizerException("error in scaling or translation: " + e.getMessage(),e);
} // end catch
} // end normalizeImage
/*--------------------------------------------------------------------------------
* Test code
*--------------------------------------------------------------------------------
*/
/**
* A simple piece of test code for the <CODE>ImageNormalizer</CODE>, which reads an image from one file,
* normalizes it, and writes it to a second file.
*
* @param args Command-line arguments. The first of these should be the name of the input file, and the
* second should be the name of the output file.
* @return (Exit code) 0 on success, 1 on error.
*/
public static void main(String[] args)
{
if (args.length<2)
{ // make sure we have 2 arguments
System.out.println("Usage: ImageNormalizer input-file output-file");
System.exit(1);
} // end if
try
{ // very simple, very easy
FileInputStream instm = new FileInputStream(args[0]);
byte[] outdata = normalizeImage(instm,100,100,"image/jpeg");
instm.close();
FileOutputStream outstm = new FileOutputStream(args[1]);
outstm.write(outdata);
outstm.close();
System.out.println(args[0] + " => " + args[1]);
} // end try
catch (Exception e)
{ // dump exception on error
e.printStackTrace();
System.exit(1);
} // end catch
System.exit(0);
} // end main
} // end class ImageNormalizer

View File

@@ -0,0 +1,77 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2003 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util.image;
/**
* Indicates an error in the image normalization process.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
* @see com.silverwrist.util.image.ImageNormalizer#normalizeImage(java.io.InputStream,int,int,java.lang.String)
*/
public class ImageNormalizerException extends Exception
{
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new <CODE>ImageNormalizerException</CODE>.
*/
public ImageNormalizerException()
{
super();
} // end constructor
/**
* Constructs a new <CODE>ImageNormalizerException</CODE>.
*
* @param message Message for the exception.
*/
public ImageNormalizerException(String message)
{
super(message);
} // end constructor
/**
* Constructs a new <CODE>ImageNormalizerException</CODE>.
*
* @param t The exception to be wrapped by this one.
*/
public ImageNormalizerException(Throwable t)
{
super(t);
} // end constructor
/**
* Constructs a new <CODE>ImageNormalizerException</CODE>.
*
* @param message Message for the exception.
* @param t The exception to be wrapped by this one.
*/
public ImageNormalizerException(String message, Throwable t)
{
super(message,t);
} // end constructor
} // end class ImageNormalizerException

View File

@@ -0,0 +1,254 @@
# The contents of this file are subject to the Mozilla Public License Version 1.1
# (the "License"); you may not use this file except in compliance with the License.
# You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
#
# Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
# WARRANTY OF ANY KIND, either express or implied. See the License for the specific
# language governing rights and limitations under the License.
#
# The Original Code is the Venice Web Communities System.
#
# The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
# for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
# Copyright (C) 2001 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
#
# Contributor(s):
# -------------------------------------------------------------------------------------
# This list of languages is styled on RFC 1766, based on ISO 639 language code listings,
# from <http://www.w3.org/WAI/ER/IG/ert/iso639.htm>, and ISO 3166 country code listings,
# from <http://www.din.de/gremien/nas/nabd/iso3166ma/>. Language variants by country taken
# from WINNT.H header file, Microsoft Windows Platform SDK. Additional language codes
# (i- names and expanded zh- names) from IANA, <ftp://ftp.isi.edu/in-notes/iana/assignments/languages/>.
# Changes to Indonesian, Hebrew, and Yiddish noted from Java 2 SDK documentation.
# When adding new entries to this file, make sure and add it in sorted order by language NAME!
# You can re-sort the language entries with "sort -t = -k 2 input > output", but then make sure
# the "i-default=(unknown)" entry appears first!
i-default=(unknown)
ab=Abkhazian
aa=Afar
af=Afrikaans
sq=Albanian
am=Amharic
i-ami=Amis
ar=Arabic
ar-DZ=Arabic (Algeria)
ar-BH=Arabic (Bahrain)
ar-EG=Arabic (Egypt)
ar-IQ=Arabic (Iraq)
ar-JO=Arabic (Jordan)
ar-KW=Arabic (Kuwait)
ar-LB=Arabic (Lebanon)
ar-LY=Arabic (Libya)
ar-MA=Arabic (Morocco)
ar-OM=Arabic (Oman)
ar-QA=Arabic (Qatar)
ar-SA=Arabic (Saudi Arabia)
ar-SY=Arabic (Syria)
ar-TN=Arabic (Tunisia)
ar-AE=Arabic (U.A.E.)
ar-YE=Arabic (Yemen)
hy=Armenian
as=Assamese
ay=Aymara
az=Azerbaijani
ba=Bashkir
eu=Basque
bn=Bengali
bh=Bihari
bi=Bislama
br=Breton
bg=Bulgarian
i-bnn=Bunun
my=Burmese
be=Byelorussian
km=Cambodian
ca=Catalan
zh=Chinese
zh-yue=Chinese (Cantonese)
zh-gan=Chinese (Gan)
zh-hakka=Chinese (Hakka)
zh-HK=Chinese (Hong Kong)
zh-xiang=Chinese (Hunan)
zh-guoyu=Chinese (Mandarin)
zh-wuu=Chinese (Shanghai)
zh-CN=Chinese (Simplified)
zh-SG=Chinese (Singapore)
zh-min=Chinese (Taiwanese)
zh-TW=Chinese (Traditional)
co=Corsican
hr=Croatian
cs=Czech
da=Danish
nl=Dutch
nl-BE=Dutch (Belgian)
dz=Dzongkha
en=English
en-AU=English (Australian)
en-BZ=English (Belize)
en-CA=English (Canadian)
en-caribbean=English (Caribbean)
en-IE=English (Irish)
en-JM=English (Jamaica)
en-NZ=English (New Zealand)
en-scouse=English (Scouse)
en-ZA=English (South Africa)
en-TT=English (Trinidad)
en-GB=English (United Kingdom)
en-US=English (United States)
eo=Esperanto
et=Estonian
fo=Faeroese
fj=Fiji
fi=Finnish
fr=French
fr-BE=French (Belgian)
fr-CA=French (Canadian)
fr-LU=French (Luxembourg)
fr-CH=French (Swiss)
fy=Frisian
gl=Gallegan
ka=Georgian
de=German
de-AT=German (Austria)
de-LI=German (Liechtenstein)
de-LU=German (Luxembourg)
de-CH=German (Swiss)
el=Greek
kl=Greenlandic
gn=Guarani
gu=Gujarati
i-hak=Hakka
ha=Hausa
he=Hebrew
hi=Hindi
hu=Hungarian
is=Icelandic
id=Indonesian
ia=Interlingua
ie=Interlingue
iu=Inuktitut
ik=Inupiak
ga=Irish
it=Italian
it-CH=Italian (Swiss)
ja=Japanese
jw=Javanese
kn=Kannada
ks=Kashmiri
km=Khmer
kk=Kazakh
rw=Kinyarwanda
ky=Kirghiz
rn=Kirundi
i-klingon=Klingon
ko=Korean
ko-johab=Korean (Johab)
ku=Kurdish
oc=Langue d'Oc
lo=Lao
la=Latin
lv=Latvian
ln=Lingala
lt=Lithuanian
i-lux=Luxembourgish
mk=Macedonian
mg=Malagasy
ms=Malay
ml=Maltese
mi=Maori
mr=Marathi
i-mingo=Mingo
mo=Moldavian
mn=Mongolian
na=Nauru
i-navajo=Navajo
ne=Nepali
no=Norwegian
no-bok=Norwegian (Bokmal)
no-nyn=Norwegian (Nynorsk)
oc=Occitan
or=Oriya
om=Oromo
i-pwn=Paiwan
pa=Panjabi
ps=Pashto
fa=Persian
pl=Polish
pt=Portuguese
pt-BR=Portuguese (Brazilian)
ps=Pushto
qu=Quechua
rm=Rhaeto-Romance
ro=Romanian
rn=Rundi
ru=Russian
sm=Samoan
sg=Sango
sa=Sanskrit
gd=Scots Gaelic
sr-cyrillic=Serbian (Cyrillic)
sr=Serbian (Latin)
sh=Serbo-Croatian
st=Sesotho
sn=Shona
sd=Sindhi
si=Singhalese
ss=Siswant
sk=Slovak
sl=Slovenian
so=Somali
st=Sotho
es-AR=Spanish (Argentina)
es-BO=Spanish (Bolivia)
es-ES=Spanish (Castilian)
es-CL=Spanish (Chile)
es-CO=Spanish (Colombia)
es-CR=Spanish (Costa Rica)
es-DO=Spanish (Dominican Republic)
es-EC=Spanish (Ecuador)
es-SV=Spanish (El Salvador)
es-GT=Spanish (Guatemala)
es-HN=Spanish (Honduras)
es-MX=Spanish (Mexican)
es=Spanish (Modern)
es-NI=Spanish (Nicaragua)
es-PA=Spanish (Panama)
es-PY=Spanish (Paraguay)
es-PE=Spanish (Peru)
es-PR=Spanish (Puerto Rico)
es-UY=Spanish (Uruguay)
es-VE=Spanish (Venezuela)
su=Sudanese
sw=Swahili
sv=Swedish
sv-FI=Swedish (Finland)
tl=Tagalog
tg=Tajik
ta=Tamil
i-tao=Tao
tt=Tatar
i-tay=Tayal
te=Tegulu
th=Thai
bo=Tibetan
ti=Tigrinya
to=Tonga
ts=Tsonga
i-tsu=Tsou
tn=Tswana
tr=Turkish
tk=Turkmen
tw=Twi
ug=Uighur
uk=Ukrainian
ur=Urdu
uz=Uzbek
vi=Vietnamese
vo=Volapuk
cy=Welsh
wo=Wolof
xh=Xhosa
yi=Yiddish
yo=Yoruba
za=Zhuang
zu=Zulu

View File

@@ -0,0 +1,489 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util.xml;
import org.w3c.dom.*;
import com.silverwrist.util.StringUtils;
/**
* A class which wraps around the DOM <CODE>Element</CODE> class, providing some
* additional functionality. Written to DOM Level 2.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
* @see org.w3c.dom.Element
*/
public final class DOMElementHelper
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Element m_elt; // element housed by this helper class
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new <CODE>DOMElementHelper</CODE> to wrap a specific <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to be wrapped.
*/
public DOMElementHelper(Element elt)
{
m_elt = elt;
} // end constructor
/*--------------------------------------------------------------------------------
* Internal static operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the content of all text nodes underneath a specified <CODE>Element</CODE>, concatenated
* together into a single string.
*
* @param e The <CODE>Element</CODE> to extract text from.
* @return The text content under this <CODE>Element</CODE> node. If the specified <CODE>Element</CODE>
* has no text nodes underneath it, returns <CODE>null.</CODE>
*/
private static final String getTextOfElement(Element e)
{
NodeList kids = e.getChildNodes();
if (kids==null)
return null; // no text?
StringBuffer b = null;
for (int i=0; i<kids.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = kids.item(i);
if ((t.getNodeType()==Node.TEXT_NODE) || (t.getNodeType()==Node.CDATA_SECTION_NODE))
{ // append to the string under construction
if (b==null)
b = new StringBuffer();
else
b.append(' ');
b.append(t.getNodeValue());
} // end if
} // end for
if (b==null)
return null; // no TEXT nodes
else
return b.toString(); // return the concatenation
} // end getTextOfElement
/**
* Returns the value of the text of the specified <CODE>Element</CODE>, expressed as an integer.
*
* @param e The <CODE>Element</CODE> to extract text from.
* @return An <CODE>Integer</CODE> object containing the value of the specified element. If
* the <CODE>Element</CODE> has no text, or if the text cannot be expressed as an integer,
* returns <CODE>null</CODE>.
*/
private static final Integer getIntegerFromElement(Element e)
{
try
{ // extract the text and create an Integer around it
String s = getTextOfElement(e);
return ((s==null) ? null : new Integer(s.trim()));
} // end try
catch (NumberFormatException nfe)
{ // value cannot be parsed as an integer
return null;
} // end catch
} // end getIntegerFromElement
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the <CODE>Element</CODE> wrapped by this object.
*
* @return See above.
*/
public final Element getElement()
{
return m_elt;
} // end getElement
/**
* Searches for the first sub-element of the wrapped <CODE>Element</CODE> with the given name.
*
* @param name Name of the sub-element to search for.
* @return The first sub-element of the wrapped <CODE>Element</CODE> with the specified name.
* If the <CODE>Element</CODE> has no child <CODE>Elements</CODE> with the given name,
* the method returns <CODE>null</CODE>.
*/
public final Element getSubElement(String name)
{
NodeList kids = m_elt.getChildNodes();
if (kids==null)
return null; // no children?
for (int i=0; i<kids.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = kids.item(i);
if ((t.getNodeType()==Node.ELEMENT_NODE) && (t.getNodeName().equals(name)))
return (Element)t;
} // end for
return null; // not found
} // end getSubElement
/**
* Searches for the first sub-element of the wrapped <CODE>Element</CODE> with the given name.
*
* @param namespaceURI Namespace URI for the sub-element to search for.
* @param name Name of the sub-element to search for.
* @return The first sub-element of the wrapped <CODE>Element</CODE> with the specified URI/name.
* If the <CODE>Element</CODE> has no child <CODE>Elements</CODE> with the given URI/name,
* the method returns <CODE>null</CODE>.
*/
public final Element getSubElementNS(String namespaceURI, String name)
{
NodeList kids = m_elt.getChildNodes();
if (kids==null)
return null; // no children?
for (int i=0; i<kids.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = kids.item(i);
if ( (t.getNodeType()==Node.ELEMENT_NODE) && t.getNamespaceURI().equals(namespaceURI)
&& t.getNodeName().equals(name))
return (Element)t;
} // end for
return null; // not found
} // end getSubElementNS
/**
* Returns the content of all text nodes underneath the wrapped <CODE>Element</CODE>, concatenated
* together into a single string.
*
* @return The text content under the wrapped <CODE>Element</CODE> node. If the wrapped <CODE>Element</CODE>
* has not text nodes underneath it, returns <CODE>null.</CODE>
*/
public final String getElementText()
{
return getTextOfElement(m_elt);
} // end getElementText
/**
* Returns the value of the text of the wrapped <CODE>Element</CODE>, expressed as an integer.
*
* @return An <CODE>Integer</CODE> object containing the value of the wrapped element. If
* the <CODE>Element</CODE> has no text, or if the text cannot be expressed as an integer,
* returns <CODE>null</CODE>.
*/
public final Integer getElementInt()
{
return getIntegerFromElement(m_elt);
} // end getElementInt
/**
* Returns the content of all text nodes underneath the first sub-element of the wrapped
* <CODE>Element</CODE>, with the given name, concatenated together into a single string.
*
* @param name The name of the sub-element to search for.
* @return The text content under the specified sub-element of the wrapped <CODE>Element</CODE> node.
* If the wrapped <CODE>Element</CODE> does not have a sub-element with the given name, or
* that sub-element has no text nodes underneath it, returns <CODE>null.</CODE>
*/
public final String getSubElementText(String name)
{
Element se = getSubElement(name);
return ((se==null) ? null : getTextOfElement(se));
} // end getSubElementText
/**
* Returns the content of all text nodes underneath the first sub-element of the wrapped
* <CODE>Element</CODE>, with the given name, concatenated together into a single string.
*
* @param namespaceURI Namespace URI for the sub-element to search for.
* @param name The name of the sub-element to search for.
* @return The text content under the specified sub-element of the wrapped <CODE>Element</CODE> node.
* If the wrapped <CODE>Element</CODE> does not have a sub-element with the given URI/name, or
* that sub-element has no text nodes underneath it, returns <CODE>null.</CODE>
*/
public final String getSubElementTextNS(String namespaceURI, String name)
{
Element se = getSubElementNS(namespaceURI,name);
return ((se==null) ? null : getTextOfElement(se));
} // end getSubElementTextNS
/**
* Returns the value of the text underneath the first sub-element of the wrapped
* <CODE>Element</CODE>, with the given name, expressed as an integer.
*
* @param name The name of the sub-element to search for.
* @return An <CODE>Integer</CODE> object containing the value of the specified element. If
* the wrapped <CODE>Element</CODE> does not have a sub-element with the given name, or that
* sub-element has no text, or if the text cannot be expressed as an integer, returns
* <CODE>null</CODE>.
*/
public final Integer getSubElementInt(String name)
{
Element se = getSubElement(name);
return ((se==null) ? null : getIntegerFromElement(se));
} // end getSubElementInt
/**
* Returns the value of the text underneath the first sub-element of the wrapped
* <CODE>Element</CODE>, with the given name, expressed as an integer.
*
* @param namespaceURI Namespace URI for the sub-element to search for.
* @param name The name of the sub-element to search for.
* @return An <CODE>Integer</CODE> object containing the value of the specified element. If
* the wrapped <CODE>Element</CODE> does not have a sub-element with the given URI/name, or that
* sub-element has no text, or if the text cannot be expressed as an integer, returns
* <CODE>null</CODE>.
*/
public final Integer getSubElementIntNS(String namespaceURI, String name)
{
Element se = getSubElementNS(namespaceURI,name);
return ((se==null) ? null : getIntegerFromElement(se));
} // end getSubElementIntNS
/**
* Determines whether the wrapped <CODE>Element</CODE> has a sub-element with the given name.
*
* @param name Name of the sub-element to search for.
* @return <CODE>true</CODE> if the wrapped <CODE>Element</CODE> has a sub-element with the
* specified name, <CODE>false</CODE> if not.
*/
public final boolean hasChildElement(String name)
{
return (getSubElement(name)!=null);
} // end hasChildElement
/**
* Determines whether the wrapped <CODE>Element</CODE> has a sub-element with the given name.
*
* @param namespaceURI Namespace URI for the sub-element to search for.
* @param name Name of the sub-element to search for.
* @return <CODE>true</CODE> if the wrapped <CODE>Element</CODE> has a sub-element with the
* specified name, <CODE>false</CODE> if not.
*/
public final boolean hasChildElementNS(String namespaceURI, String name)
{
return (getSubElementNS(namespaceURI,name)!=null);
} // end hasChildElementNS
/**
* Determines whether the wrapped <CODE>Element</CODE> has an attribute with the given name.
*
* @param name Name of the attribute to search for.
* @return <CODE>true</CODE> if the wrapped <CODE>Element</CODE> has an attribute with the
* specified name, <CODE>false</CODE> if not.
*/
public final boolean hasAttribute(String name)
{
return m_elt.hasAttribute(name);
} // end hasAttribute
/**
* Determines whether the wrapped <CODE>Element</CODE> has an attribute with the given name.
*
* @param namespaceURI Namespace URI for the attribute to search for.
* @param name Name of the attribute to search for.
* @return <CODE>true</CODE> if the wrapped <CODE>Element</CODE> has an attribute with the
* specified URI/name, <CODE>false</CODE> if not.
*/
public final boolean hasAttributeNS(String namespaceURI, String name)
{
return m_elt.hasAttributeNS(namespaceURI,name);
} // end hasAttributeNS
/**
* Returns the value of a specified attribute of the wrapped <CODE>Element</CODE>, expressed as
* an integer.
*
* @param name Name of the attribute to search for.
* @return An <CODE>Integer</CODE> object containing the value of the specified attribute. If
* the wrapped <CODE>Element</CODE> has no such attribute, or if the attribute's value
* cannot be expressed as an integer, returns <CODE>null</CODE>.
*/
public final Integer getAttributeInt(String name)
{
String tmp = m_elt.getAttribute(name);
if (StringUtils.isEmpty(tmp))
return null;
try
{ // convert to an Integer
return new Integer(tmp.trim());
} // end try
catch (NumberFormatException nfe)
{ // return a null value on error
return null;
} // end catch
} // end getAttributeInt
/**
* Returns the value of a specified attribute of the wrapped <CODE>Element</CODE>, expressed as
* an integer.
*
* @param namespaceURI Namespace URI for the attribute to search for.
* @param name Name of the attribute to search for.
* @return An <CODE>Integer</CODE> object containing the value of the specified attribute. If
* the wrapped <CODE>Element</CODE> has no such attribute, or if the attribute's value
* cannot be expressed as an integer, returns <CODE>null</CODE>.
*/
public final Integer getAttributeIntNS(String namespaceURI, String name)
{
String tmp = m_elt.getAttributeNS(namespaceURI,name);
if (StringUtils.isEmpty(tmp))
return null;
try
{ // convert to an Integer
return new Integer(tmp.trim());
} // end try
catch (NumberFormatException nfe)
{ // return a null value on error
return null;
} // end catch
} // end getAttributeInt
/**
* Returns the value of a specified attribute of the wrapped <CODE>Element</CODE>, expressed as
* a Boolean. Uses the Boolean string methods on {@link com.silverwrist.util.StringUtils StringUtils} to
* determine the state of the attribute value.
*
* @param name Name of the attribute to search for.
* @return <CODE>Boolean.TRUE</CODE> if the attribute value represents a "true" Boolean value;
* <CODE>Boolean.FALSE</CODE> if the attribute value represents a "false" Boolean value; <CODE>null</CODE>
* otherwise.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final Boolean getAttributeBoolean(String name)
{
String tmp = m_elt.getAttribute(name);
if (StringUtils.isBooleanTrue(tmp))
return Boolean.TRUE;
else if (StringUtils.isBooleanFalse(tmp))
return Boolean.FALSE;
else
return null;
} // end getAttributeBoolean
/**
* Returns the value of a specified attribute of the wrapped <CODE>Element</CODE>, expressed as
* a Boolean. Uses the Boolean string methods on {@link com.silverwrist.util.StringUtils StringUtils} to
* determine the state of the attribute value.
*
* @param namespaceURI Namespace URI for the attribute to search for.
* @param name Name of the attribute to search for.
* @return <CODE>Boolean.TRUE</CODE> if the attribute value represents a "true" Boolean value;
* <CODE>Boolean.FALSE</CODE> if the attribute value represents a "false" Boolean value; <CODE>null</CODE>
* otherwise.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final Boolean getAttributeBooleanNS(String namespaceURI, String name)
{
String tmp = m_elt.getAttributeNS(namespaceURI,name);
if (StringUtils.isBooleanTrue(tmp))
return Boolean.TRUE;
else if (StringUtils.isBooleanFalse(tmp))
return Boolean.FALSE;
else
return null;
} // end getAttributeBooleanNS
/**
* Returns the value of a specified attribute of the wrapped <CODE>Element</CODE>, expressed as
* a Boolean. Uses the Boolean string methods on {@link com.silverwrist.util.StringUtils StringUtils} to
* determine the state of the attribute value.
*
* @param name Name of the attribute to search for.
* @param default_val Default value for the attribute.
* @return <CODE>Boolean.TRUE</CODE> if the attribute value represents a "true" Boolean value;
* <CODE>Boolean.FALSE</CODE> if the attribute value represents a "false" Boolean value; the
* <CODE>Boolean</CODE> object corresponding to <CODE>default_val</CODE> if the attribute is missing;
* <CODE>null</CODE> otherwise.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final Boolean getAttributeBoolean(String name, boolean default_val)
{
if (this.hasAttribute(name))
return this.getAttributeBoolean(name);
else
return (default_val ? Boolean.TRUE : Boolean.FALSE);
} // end getAttributeBoolean
/**
* Returns the value of a specified attribute of the wrapped <CODE>Element</CODE>, expressed as
* a Boolean. Uses the Boolean string methods on {@link com.silverwrist.util.StringUtils StringUtils} to
* determine the state of the attribute value.
*
* @param namespaceURI Namespace URI for the attribute to search for.
* @param name Name of the attribute to search for.
* @param default_val Default value for the attribute.
* @return <CODE>Boolean.TRUE</CODE> if the attribute value represents a "true" Boolean value;
* <CODE>Boolean.FALSE</CODE> if the attribute value represents a "false" Boolean value; the
* <CODE>Boolean</CODE> object corresponding to <CODE>default_val</CODE> if the attribute is missing;
* <CODE>null</CODE> otherwise.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final Boolean getAttributeBooleanNS(String namespaceURI, String name, boolean default_val)
{
if (this.hasAttributeNS(namespaceURI,name))
return this.getAttributeBooleanNS(namespaceURI,name);
else
return (default_val ? Boolean.TRUE : Boolean.FALSE);
} // end getAttributeBooleanNS
} // end class DOMElementHelper

View File

@@ -0,0 +1,155 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util.xml;
import org.w3c.dom.*;
/**
* An exception type thrown by the {@link com.silverwrist.util.xml.XMLLoader XMLLoader} when it encounters
* a parse error, value error, or other erroneous condition. It contains a reference to the node in the DOM
* tree where the error occured, if such is possible to determine.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class XMLLoadException extends Exception
{
/*--------------------------------------------------------------------------------
* Attributes
*--------------------------------------------------------------------------------
*/
private Node m_locus = null; // locus of the error
/*--------------------------------------------------------------------------------
* Constructors
*--------------------------------------------------------------------------------
*/
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*/
public XMLLoadException()
{
super();
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param msg The error message to be thrown.
*/
public XMLLoadException(String msg)
{
super(msg);
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param inner The exception wrapped by this <CODE>XMLLoadException</CODE>.
*/
public XMLLoadException(Throwable inner)
{
super(inner);
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param msg The error message to be thrown.
* @param inner The exception wrapped by this <CODE>XMLLoadException</CODE>.
*/
public XMLLoadException(String msg, Throwable inner)
{
super(msg,inner);
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param locus The <CODE>Node</CODE> in the DOM tree where the error occurred.
*/
public XMLLoadException(Node locus)
{
super("Error in <" + locus.getNodeName() + "/> section of input");
m_locus = locus;
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param msg The error message to be thrown.
* @param locus The <CODE>Node</CODE> in the DOM tree where the error occurred.
*/
public XMLLoadException(String msg, Node locus)
{
super("Error in <" + locus.getNodeName() + "/> section of input - " + msg);
m_locus = locus;
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param inner The exception wrapped by this <CODE>XMLLoadException</CODE>.
* @param locus The <CODE>Node</CODE> in the DOM tree where the error occurred.
*/
public XMLLoadException(Throwable inner, Node locus)
{
super("Error in <" + locus.getNodeName() + "/> section of input - " + inner.getMessage(),inner);
m_locus = locus;
} // end constructor
/**
* Constructs a new <CODE>XMLLoadException</CODE>.
*
* @param msg The error message to be thrown.
* @param inner The exception wrapped by this <CODE>XMLLoadException</CODE>.
* @param locus The <CODE>Node</CODE> in the DOM tree where the error occurred.
*/
public XMLLoadException(String msg, Throwable inner, Node locus)
{
super("Error in <" + locus.getNodeName() + "/> section of input - " + msg,inner);
m_locus = locus;
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Returns the locus of the error contained in this exception.
*
* @return The <CODE>Node</CODE> that indicates wherre in the DOM tree the error occurred.
*/
public Node getLocus()
{
return m_locus;
} // end getLocus
} // end class XMLLoadException

View File

@@ -0,0 +1,824 @@
/*
* The contents of this file are subject to the Mozilla Public License Version 1.1
* (the "License"); you may not use this file except in compliance with the License.
* You may obtain a copy of the License at <http://www.mozilla.org/MPL/>.
*
* Software distributed under the License is distributed on an "AS IS" basis, WITHOUT
* WARRANTY OF ANY KIND, either express or implied. See the License for the specific
* language governing rights and limitations under the License.
*
* The Original Code is the Venice Web Communities System.
*
* The Initial Developer of the Original Code is Eric J. Bowersox <erbo@silcom.com>,
* for Silverwrist Design Studios. Portions created by Eric J. Bowersox are
* Copyright (C) 2002-03 Eric J. Bowersox/Silverwrist Design Studios. All Rights Reserved.
*
* Contributor(s):
*/
package com.silverwrist.util.xml;
import java.io.*;
import java.util.*;
import javax.xml.parsers.*;
import org.apache.log4j.Logger;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import com.silverwrist.util.StringUtils;
/**
* A simple class which is commonly used for the loading of XML documents as configuration files. Various
* methods on this object load XML documents as DOM trees and extract portions of the information therein.
* It is implemented as a Singleton.
*
* @author Eric J. Bowersox &lt;erbo@silcom.com&gt;
* @version X
*/
public class XMLLoader
{
/*--------------------------------------------------------------------------------
* Static data members
*--------------------------------------------------------------------------------
*/
private static Logger logger = Logger.getLogger(XMLLoader.class);
private static XMLLoader self = null; // our singleton instance
/*--------------------------------------------------------------------------------
* Constructor
*--------------------------------------------------------------------------------
*/
/**
* Internal constructor for <CODE>XMLLoader</CODE>. Only one instance is ever constructed.
*/
private XMLLoader()
{ // do nothing
} // end constructor
/*--------------------------------------------------------------------------------
* External operations
*--------------------------------------------------------------------------------
*/
/**
* Parses an XML document into a DOM tree.
*
* @param stm The XML document to be parsed, expressed as an <CODE>InputStream</CODE>.
* @param namespacing <CODE>true</CODE> if we want this XML document parsed in a namespace-aware fashion,
* <CODE>false</CODE> if not.
* @return The <CODE>Document</CODE> that results from parsing the XML document.
* @exception java.io.IOException If there was an I/O error reading from the XML document.
* @exception com.silverwrist.util.xml.XMLLoaderException If there was a parse error in the XML, or other error
* accessing the XML parser.
*/
public final Document load(InputStream stm, boolean namespacing) throws IOException, XMLLoadException
{
try
{ // create a simple DOM parser by using the Java XML parsing API
DocumentBuilderFactory fac = DocumentBuilderFactory.newInstance();
fac.setNamespaceAware(namespacing);
fac.setValidating(false);
DocumentBuilder parser = fac.newDocumentBuilder();
if (parser.isNamespaceAware()!=namespacing)
throw new XMLLoadException("XML parser namespacing parameter is not consistent");
// access the config file and parse it into our config data tree
return parser.parse(stm);
} // end try
catch (FactoryConfigurationError fce)
{ // if the document builder factory could not be created
throw new XMLLoadException("XML parser factory could not be created - " + fce.getMessage());
} // end catch
catch (ParserConfigurationException pce)
{ // if the XML parser itself could not be created
throw new XMLLoadException("XML parser could not be created - " + pce.getMessage(),pce);
} // end catch
catch (SAXException se)
{ // if the XML parser choked on our document
if (se instanceof SAXParseException)
{ // we have a detailed message - make a proper exception
SAXParseException spe = (SAXParseException)se;
throw new XMLLoadException("Error in XML data: " + spe.getMessage() + " at line "
+ spe.getLineNumber() + ", column " + spe.getColumnNumber(),spe);
} // end if
else
{ // generic exception - just send up a simple error message
throw new XMLLoadException("Error in XML data - " + se.getMessage(),se);
} // end else
} // end catch
} // end load
/**
* Parses an XML document into a DOM tree.
*
* @param stm The XML document to be parsed, expressed as a <CODE>File</CODE> object.
* @param namespacing <CODE>true</CODE> if we want this XML document parsed in a namespace-aware fashion,
* <CODE>false</CODE> if not.
* @return The <CODE>Document</CODE> that results from parsing the XML document.
* @exception java.io.IOException If there was an I/O error reading from the XML document.
* @exception com.silverwrist.util.xml.XMLLoaderException If there was a parse error in the XML, or other error
* accessing the XML parser.
*/
public final Document load(File file, boolean namespacing) throws IOException, XMLLoadException
{
return this.load(new FileInputStream(file),namespacing);
} // end load
/**
* Gets the root element of a parsed XML DOM tree, and verifies that it matches a specific name.
*
* @param doc The document to get the root element of.
* @param expected_name The expected name of the root element.
* @return The root <CODE>Element</CODE> of the document,
* @exception com.silverwrist.util.XMLLoadException If the root element of the document does not match the
* <CODE>expected_name</CODE>.
*/
public final Element getRootElement(Document doc, String expected_name) throws XMLLoadException
{
Element rc = doc.getDocumentElement();
if (rc.getTagName().equals(expected_name))
return rc; // we're OK
throw new XMLLoadException("expected <" + expected_name + "/> root element",rc);
} // end getRootElement
/**
* Gets the root element of a parsed XML DOM tree, and verifies that it matches a specific name.
*
* @param doc The document to get the root element of.
* @param expected_namespace The expected namespace for the root element of the document.
* @param expected_name The expected name of the root element.
* @return The root <CODE>Element</CODE> of the document,
* @exception com.silverwrist.util.XMLLoadException If the root element of the document does not match the
* <CODE>expected_namespace</CODE> and <CODE>expected_name</CODE>.
*/
public final Element getRootElementNS(Document doc, String expected_namespace,
String expected_name) throws XMLLoadException
{
Element rc = doc.getDocumentElement();
if (rc.getNamespaceURI().equals(expected_namespace) && rc.getTagName().equals(expected_name))
return rc; // we're OK
throw new XMLLoadException("expected <" + expected_namespace + ":" + expected_name + "/> root element",rc);
} // end getRootElementNS
/**
* Gets the text contained in an <CODE>Element</CODE> wrapped in a
* {@link com.silverwrist.util.xml.DOMElementHelper DOMElementHelper}.
*
* @param h The <CODE>DOMElementHelper</CODE> to extract the text from.
* @return The text contained in the element.
* @exception com.silverwrist.util.XMLLoadException If there is no text contained in the element.
*/
public final String getText(DOMElementHelper h) throws XMLLoadException
{
String rc = h.getElementText();
if (rc!=null)
return rc; // we're OK
throw new XMLLoadException("no text found under element",h.getElement());
} // end getText
/**
* Gets the text contained in an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to extract the text from.
* @return The text contained in the element.
* @exception com.silverwrist.util.XMLLoadException If there is no text contained in the element.
*/
public final String getText(Element elt) throws XMLLoadException
{
return getText(new DOMElementHelper(elt));
} // end getText
/**
* Gets the text contained in a named sub-element of an <CODE>Element</CODE> wrapped in a
* {@link com.silverwrist.util.xml.DOMElementHelper DOMElementHelper}.
*
* @param h The <CODE>DOMElementHelper</CODE> to extract the text from.
* @param elt_name The name of the sub-element to look for text in.
* @return The text contained in the sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found, or there is no text
* contained in the sub-element.
*/
public final String getSubElementText(DOMElementHelper h, String elt_name) throws XMLLoadException
{
String rc = h.getSubElementText(elt_name);
if (rc!=null)
return rc; // we're OK
throw new XMLLoadException("sublement <" + elt_name + "/> not found",h.getElement());
} // end getSubElementText
/**
* Gets the text contained in a named sub-element of an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to extract the text from.
* @param subelt_name The name of the sub-element to look for text in.
* @return The text contained in the sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found, or there is no text
* contained in the sub-element.
*/
public final String getSubElementText(Element elt, String subelt_name) throws XMLLoadException
{
return getSubElementText(new DOMElementHelper(elt),subelt_name);
} // end getSubElementText
/**
* Gets the text contained in a named sub-element of an <CODE>Element</CODE> wrapped in a
* {@link com.silverwrist.util.xml.DOMElementHelper DOMElementHelper}.
*
* @param h The <CODE>DOMElementHelper</CODE> to extract the text from.
* @param namespace The namespace URI of the sub-element to look for text in.
* @param elt_name The name of the sub-element to look for text in.
* @return The text contained in the sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found, or there is no text
* contained in the sub-element.
*/
public final String getSubElementTextNS(DOMElementHelper h, String namespace, String elt_name)
throws XMLLoadException
{
String rc = h.getSubElementTextNS(namespace,elt_name);
if (rc!=null)
return rc; // we're OK
throw new XMLLoadException("sublement <" + namespace + ":" + elt_name + "/> not found",h.getElement());
} // end getSubElementTextNS
/**
* Gets the text contained in a named sub-element of an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to extract the text from.
* @param namespace The namespace URI of the sub-element to look for text in.
* @param subelt_name The name of the sub-element to look for text in.
* @return The text contained in the sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found, or there is no text
* contained in the sub-element.
*/
public final String getSubElementTextNS(Element elt, String namespace, String subelt_name)
throws XMLLoadException
{
return getSubElementTextNS(new DOMElementHelper(elt),namespace,subelt_name);
} // end getSubElementTextNS
/**
* Gets a named sub-element of an <CODE>Element</CODE> wrapped in a
* {@link com.silverwrist.util.xml.DOMElementHelper DOMElementHelper}.
*
* @param h The <CODE>DOMElementHelper</CODE> to extract the sub-element from.
* @param name The name of the sub-element to look for.
* @return The sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found.
*/
public final Element getSubElement(DOMElementHelper h, String name) throws XMLLoadException
{
Element rc = h.getSubElement(name);
if (rc!=null)
return rc; // we're OK
throw new XMLLoadException("sublement <" + name + "/> not found",h.getElement());
} // end getSubElement
/**
* Gets a named sub-element of an <CODE>Element</CODE>.
*
* @param sect The <CODE>Element</CODE> to extract the sub-element from.
* @param name The name of the sub-element to look for.
* @return The sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found.
*/
public final Element getSubElement(Element sect, String name) throws XMLLoadException
{
return getSubElement(new DOMElementHelper(sect),name);
} // end getSubElement
/**
* Gets a named sub-element of an <CODE>Element</CODE> wrapped in a
* {@link com.silverwrist.util.xml.DOMElementHelper DOMElementHelper}.
*
* @param h The <CODE>DOMElementHelper</CODE> to extract the sub-element from.
* @param namespace The namespace URI of the sub-element to look for.
* @param name The name of the sub-element to look for.
* @return The sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found.
*/
public final Element getSubElementNS(DOMElementHelper h, String namespace, String name)
throws XMLLoadException
{
Element rc = h.getSubElementNS(namespace,name);
if (rc!=null)
return rc; // we're OK
throw new XMLLoadException("sublement <" + namespace + ":" + name + "/> not found",h.getElement());
} // end getSubElementNS
/**
* Gets a named sub-element of an <CODE>Element</CODE>.
*
* @param sect The <CODE>Element</CODE> to extract the sub-element from.
* @param namespace The namespace URI of the sub-element to look for.
* @param name The name of the sub-element to look for.
* @return The sub-element.
* @exception com.silverwrist.util.XMLLoadException If the sub-element is not found.
*/
public final Element getSubElementNS(Element sect, String namespace, String name) throws XMLLoadException
{
return getSubElementNS(new DOMElementHelper(sect),namespace,name);
} // end getSubElementNS
/**
* Returns all sub-elements of an <CODE>Element</CODE> element that have a specific name.
*
* @param sect The <CODE>Element</CODE> to extract the sub-elements from.
* @param name The name of the sub-elements to look for.
* @return A <CODE>java.util.List</CODE> containing all the sub-elements of the given <CODE>Element</CODE> with
* the specified name. If there are no matching sub-elements, an empty list is returned.
*/
public final List getMatchingSubElements(Element sect, String name)
{
ArrayList rc = new ArrayList();
NodeList nl = sect.getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = nl.item(i);
if ((t.getNodeType()==Node.ELEMENT_NODE) && t.getNodeName().equals(name))
rc.add((Element)t);
} // end for
if (rc.isEmpty())
return Collections.EMPTY_LIST;
rc.trimToSize();
return Collections.unmodifiableList(rc);
} // end getMatchingSubElements
/**
* Returns all sub-elements of an <CODE>Element</CODE> element that have a specific name.
*
* @param sect The <CODE>Element</CODE> to extract the sub-elements from.
* @param namespace The namespace URI of the sub-elements to look for.
* @param name The name of the sub-elements to look for.
* @return A <CODE>java.util.List</CODE> containing all the sub-elements of the given <CODE>Element</CODE> with
* the specified namespace and name. If there are no matching sub-elements, an empty list is returned.
*/
public final List getMatchingSubElementsNS(Element sect, String namespace, String name)
{
ArrayList rc = new ArrayList();
NodeList nl = sect.getChildNodes();
for (int i=0; i<nl.getLength(); i++)
{ // look for an ELEMENT_NODE node matching the desired name
Node t = nl.item(i);
if ( (t.getNodeType()==Node.ELEMENT_NODE) && t.getNamespaceURI().equals(namespace)
&& t.getNodeName().equals(name))
rc.add((Element)t);
} // end for
if (rc.isEmpty())
return Collections.EMPTY_LIST;
rc.trimToSize();
return Collections.unmodifiableList(rc);
} // end getMatchingSubElementsNS
/**
* Checks to make sure that the name of a given node is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param n The <CODE>Node</CODE> to test the name of.
* @param name The name to test the node against.
* @param enclosing_sect The <CODE>Element</CODE> that contains this node as a child, used in constructing
* the exception if the test fails.
* @exception com.silverwrist.util.xml.XMLLoadException If the name of the node does not match.
*/
public final void verifyNodeName(Node n, String name, Element enclosing_sect) throws XMLLoadException
{
if (n.getNodeName().equals(name))
return;
throw new XMLLoadException("node <" + n.getNodeName() + "/> should be <" + name + "/>",enclosing_sect);
} // end verifyNodeName
/**
* Checks to make sure that the name of a given node is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param n The <CODE>Node</CODE> to test the name of.
* @param name The name to test the node against.
* @exception com.silverwrist.util.xml.XMLLoadException If the name of the node does not match.
*/
public final void verifyNodeName(Node n, String name) throws XMLLoadException
{
verifyNodeName(n,name,(Element)(n.getParentNode()));
} // end verifyNodeName
/**
* Checks to make sure that the name of a given node is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param n The <CODE>Node</CODE> to test the name of.
* @param namespace The namespace URI to test the node against.
* @param name The name to test the node against.
* @param enclosing_sect The <CODE>Element</CODE> that contains this node as a child, used in constructing
* the exception if the test fails.
* @exception com.silverwrist.util.xml.XMLLoadException If the name of the node does not match.
*/
public final void verifyNodeNameNS(Node n, String namespace, String name, Element enclosing_sect)
throws XMLLoadException
{
if (n.getNamespaceURI().equals(namespace) && n.getNodeName().equals(name))
return;
throw new XMLLoadException("node <" + n.getNamespaceURI() + ":" + n.getNodeName() + "/> should be <"
+ namespace + ":" + name + "/>",enclosing_sect);
} // end verifyNodeNameNS
/**
* Checks to make sure that the name of a given node is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param n The <CODE>Node</CODE> to test the name of.
* @param namespace The namespace URI to test the node against.
* @param name The name to test the node against.
* @exception com.silverwrist.util.xml.XMLLoadException If the name of the node does not match.
*/
public final void verifyNodeNameNS(Node n, String namespace, String name) throws XMLLoadException
{
verifyNodeNameNS(n,namespace,name,(Element)(n.getParentNode()));
} // end verifyNodeNameNS
/**
* Checks to make sure that the name of a given tag element is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param tag The <CODE>Element</CODE> to test the name of.
* @param name The name to test the element against.
* @exception com.silverwrist.util.xml.XMLLoadException If the name of the element does not match.
*/
public final void verifyTagName(Element tag, String name) throws XMLLoadException
{
if (tag.getTagName().equals(name))
return;
throw new XMLLoadException("expected <" + name + "/> element",tag);
} // end verifyTagName
/**
* Checks to make sure that the name of a given tag element is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param tag The <CODE>Element</CODE> to test the name of.
* @param namespace The namespace URI to test the element against.
* @param name The name to test the element against.
* @exception com.silverwrist.util.xml.XMLLoadException If the name of the element does not match.
*/
public final void verifyTagNameNS(Element tag, String namespace, String name) throws XMLLoadException
{
if (tag.getNamespaceURI().equals(namespace) && tag.getTagName().equals(name))
return;
throw new XMLLoadException("expected <" + namespace + ":" + name + "/> element",tag);
} // end verifyTagNameNS
/**
* Gets the value of an attribute on an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param attr_name The name of the attribute to retrieve.
* @return The attribute value.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute did not exist on the element.
*/
public final String getAttribute(Element elt, String attr_name) throws XMLLoadException
{
String rc = elt.getAttribute(attr_name);
if (!(StringUtils.isEmpty(rc)))
return rc;
throw new XMLLoadException("no " + attr_name + "= attribute found",elt);
} // end getAttribute
/**
* Gets the value of an attribute on an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param attr_name The name of the attribute to retrieve.
* @param default_val The default value of the attribute.
* @return The attribute value, or the value of <CODE>default_val</CODE> if the attribute didn't exist.
*/
public final String getAttribute(Element elt, String attr_name, String default_val)
{
String rc = elt.getAttribute(attr_name);
return (StringUtils.isEmpty(rc) ? default_val : rc);
} // end getAttribute
/**
* Gets the value of an attribute on an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param namespace The namespace URI of the attribute to retrieve.
* @param attr_name The name of the attribute to retrieve.
* @return The attribute value.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute did not exist on the element.
*/
public final String getAttributeNS(Element elt, String namespace, String attr_name) throws XMLLoadException
{
String rc = elt.getAttributeNS(namespace,attr_name);
if (!(StringUtils.isEmpty(rc)))
return rc;
throw new XMLLoadException("no " + namespace + ":" + attr_name + "= attribute found",elt);
} // end getAttributeNS
/**
* Gets the value of an attribute on an <CODE>Element</CODE>.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param namespace The namespace URI of the attribute to retrieve.
* @param attr_name The name of the attribute to retrieve.
* @param default_val The default value of the attribute.
* @return The attribute value, or the value of <CODE>default_val</CODE> if the attribute didn't exist.
*/
public final String getAttributeNS(Element elt, String namespace, String attr_name, String default_val)
{
String rc = elt.getAttributeNS(namespace,attr_name);
return (StringUtils.isEmpty(rc) ? default_val : rc);
} // end getAttributeNS
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as an integer.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param attr_name The name of the attribute to retrieve.
* @return The attribute value.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute did not exist on the element, or
* it could not be parsed as an integer.
*/
public final int getAttributeInt(Element elt, String attr_name) throws XMLLoadException
{
String tmp = elt.getAttribute(attr_name);
if (StringUtils.isEmpty(tmp))
{ // the attribute is not present
throw new XMLLoadException("no " + attr_name + "= attribute found",elt);
} // end if
try
{ // parse out the integer value
return Integer.parseInt(tmp.trim());
} // end try
catch (NumberFormatException nfe)
{ // but it's not a valid integer - throw something else!
throw new XMLLoadException(attr_name + "= attribute value is not a valid integer",elt);
} // end catch
} // end getAttributeInt
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as an integer.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param attr_name The name of the attribute to retrieve.
* @param default_val The default value of the attribute.
* @return The attribute value, or the value of <CODE>default_val</CODE> if the attribute didn't exist.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute could not be parsed as an integer.
*/
public final int getAttributeInt(Element elt, String attr_name, int default_val) throws XMLLoadException
{
String tmp = elt.getAttribute(attr_name);
if (StringUtils.isEmpty(tmp))
return default_val; // the attribute is not present
try
{ // parse out the integer value
return Integer.parseInt(tmp.trim());
} // end try
catch (NumberFormatException nfe)
{ // but it's not a valid integer - throw something else!
throw new XMLLoadException(attr_name + "= attribute value is not a valid integer",elt);
} // end catch
} // end getAttributeInt
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as an integer.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param namespace The namespace URI of the attribute to retrieve.
* @param attr_name The name of the attribute to retrieve.
* @return The attribute value.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute did not exist on the element, or
* it could not be parsed as an integer.
*/
public final int getAttributeIntNS(Element elt, String namespace, String attr_name) throws XMLLoadException
{
String tmp = elt.getAttributeNS(namespace,attr_name);
if (StringUtils.isEmpty(tmp))
{ // the attribute is not present
throw new XMLLoadException("no " + namespace + ":" + attr_name + "= attribute found",elt);
} // end if
try
{ // parse out the integer value
return Integer.parseInt(tmp.trim());
} // end try
catch (NumberFormatException nfe)
{ // but it's not a valid integer - throw something else!
throw new XMLLoadException(namespace + ":" + attr_name + "= attribute value is not a valid integer",elt);
} // end catch
} // end getAttributeIntNS
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as an integer.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param namespace The namespace URI of the attribute to retrieve.
* @param attr_name The name of the attribute to retrieve.
* @param default_val The default value of the attribute.
* @return The attribute value, or the value of <CODE>default_val</CODE> if the attribute didn't exist.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute could not be parsed as an integer.
*/
public final int getAttributeIntNS(Element elt, String namespace, String attr_name, int default_val)
throws XMLLoadException
{
String tmp = elt.getAttributeNS(namespace,attr_name);
if (StringUtils.isEmpty(tmp))
return default_val; // the attribute is not present
try
{ // parse out the integer value
return Integer.parseInt(tmp.trim());
} // end try
catch (NumberFormatException nfe)
{ // but it's not a valid integer - throw something else!
throw new XMLLoadException(namespace + ":" + attr_name + "= attribute value is not a valid integer",elt);
} // end catch
} // end getAttributeIntNS
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as a Boolean. Uses the Boolean string
* methods on {@link com.silverwrist.util.StringUtils StringUtils} to determine the state of the attribute value.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param attr_name The name of the attribute to retrieve.
* @return The attribute value.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute did not exist on the element, or
* it could not be parsed as a Boolean.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final boolean getAttributeBoolean(Element elt, String attr_name)
throws XMLLoadException
{
String tmp = elt.getAttribute(attr_name);
if (StringUtils.isEmpty(tmp))
throw new XMLLoadException("no " + attr_name + "= attribute found",elt);
if (StringUtils.isBooleanTrue(tmp))
return true;
if (StringUtils.isBooleanFalse(tmp))
return false;
throw new XMLLoadException(attr_name + "= attribute value is not a valid Boolean",elt);
} // end getAttributeBoolean
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as a Boolean. Uses the Boolean string
* methods on {@link com.silverwrist.util.StringUtils StringUtils} to determine the state of the attribute value.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param attr_name The name of the attribute to retrieve.
* @param default_val The default value of the attribute.
* @return The attribute value, or the value of <CODE>default_val</CODE> if the attribute didn't exist.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute could not be parsed as a Boolean.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final boolean getAttributeBoolean(Element elt, String attr_name, boolean default_val)
throws XMLLoadException
{
String tmp = elt.getAttribute(attr_name);
if (StringUtils.isEmpty(tmp))
return default_val;
if (StringUtils.isBooleanTrue(tmp))
return true;
if (StringUtils.isBooleanFalse(tmp))
return false;
throw new XMLLoadException(attr_name + "= attribute value is not a valid Boolean",elt);
} // end getAttributeBoolean
/**
* Gets the value of an attribute on an <CODE>Element</CODE>, expressed as a Boolean. Uses the Boolean string
* methods on {@link com.silverwrist.util.StringUtils StringUtils} to determine the state of the attribute value.
*
* @param elt The <CODE>Element</CODE> to retrieve the attribute from.
* @param namespace The namespace URI of the attribute to retrieve.
* @param attr_name The name of the attribute to retrieve.
* @param default_val The default value of the attribute.
* @return The attribute value, or the value of <CODE>default_val</CODE> if the attribute didn't exist.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute could not be parsed as a Boolean.
* @see com.silverwrist.util.StringUtils#isBooleanTrue(java.lang.String)
* @see com.silverwrist.util.StringUtils#isBooleanFalse(java.lang.String)
*/
public final boolean getAttributeBooleanNS(Element elt, String namespace, String attr_name,
boolean default_val) throws XMLLoadException
{
String tmp = elt.getAttributeNS(namespace,attr_name);
if (StringUtils.isEmpty(tmp))
return default_val;
if (StringUtils.isBooleanTrue(tmp))
return true;
if (StringUtils.isBooleanFalse(tmp))
return false;
throw new XMLLoadException(namespace + ":" + attr_name + "= attribute value is not a valid Boolean",elt);
} // end getAttributeBooleanNS
/**
* Checks to make sure that the value of a given attribute is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param elt The <CODE>Element</CODE> to test the attribute of.
* @param attr_name The name of the attribute to test.
* @param attr_value The value to test the attribute against.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute does not exist, or its value does not match.
*/
public final void verifyAttributeValue(Element elt, String attr_name, String attr_value)
throws XMLLoadException
{
String tmp = this.getAttribute(elt,attr_name);
if (!(tmp.equals(attr_value)))
throw new XMLLoadException("attribute " + attr_name + "= should be '" + attr_value + "', but is '"
+ tmp + "'",elt);
} // end verifyAttributeValue
/**
* Checks to make sure that the value of a given attribute is what we expect, and throws an
* {@link com.silverwrist.util.xml.XMLLoadException XMLLoadException} if it isn't.
*
* @param elt The <CODE>Element</CODE> to test the attribute of.
* @param namespace The namespace URI of the attribute to test.
* @param attr_name The name of the attribute to test.
* @param attr_value The value to test the attribute against.
* @exception com.silverwrist.util.xml.XMLLoadException If the attribute does not exist, or its value does not match.
*/
public final void verifyAttributeValueNS(Element elt, String namespace, String attr_name, String attr_value)
throws XMLLoadException
{
String tmp = this.getAttributeNS(elt,namespace,attr_name);
if (!(tmp.equals(attr_value)))
throw new XMLLoadException("attribute " + namespace + ":" + attr_name + "= should be '" + attr_value
+ "', but is '" + tmp + "'",elt);
} // end verifyAttributeValueNS
/*--------------------------------------------------------------------------------
* External static operations
*--------------------------------------------------------------------------------
*/
/**
* Gets the Singleton instance of the <CODE>XMLLoader</CODE> object.
*
* @return The Singleton instance of the <CODE>XMLLoader</CODE> object.
*/
public static final synchronized XMLLoader get()
{
if (self==null)
self = new XMLLoader();
return self;
} // end get
} // end class XMLLoader