protected void firePropertyChanged(PropertyEvent event)
   {
      // fire all bound listeners (if any) first
      if (boundListeners != null)
      {
         List list = (List) boundListeners.get(event.getPropertyName());
         if (list != null)
         {
            firePropertyChanged(list, event);
         }
      }

      // next fire all unbound listeners
      firePropertyChanged(unboundListeners, event);
   }

Fire a property changed event to all listeners.

@param event   Property event.

Fire a property changed event to all listeners .


protected String makePrefixedPropertyName(String base, String prefix)
   {
      String name = base;

      if (prefix != null)
      {
         StringBuffer buff = new StringBuffer(base);
         if (prefix != null)
         {
            buff.insert(0, PROPERTY_NAME_SEPARATOR);
            buff.insert(0, prefix);
         }
         return buff.toString();
      }

      return name;
   }

protected String makePrefixedPropertyName ( String base , String prefix ) { String name = base ; if ( prefix != null ) { StringBuffer buff = new StringBuffer ( base ) ; if ( prefix != null ) { buff . insert ( 0 , PROPERTY_NAME_SEPARATOR ) ; buff . insert ( 0 , prefix ) ; } return buff . toString ( ) ; } return name ; }

Make a optionaly prefixed property name.

@param base    Base property name.
@param prefix  Optional prefix (can be null).
@return        Property name.

Make a optionaly prefixed property name .


public void load(PropertyReader reader) throws PropertyException, IOException
   {
      if (reader == null)
         throw new NullArgumentException("reader");

      load(reader.readProperties());
   }

public void load ( PropertyReader reader ) throws PropertyException , IOException { if ( reader == null ) throw new NullArgumentException ( "reader" ) ; load ( reader . readProperties ( ) ) ; }

Load properties from a PropertyReader.

@param reader  PropertyReader to read properties from.
@throws PropertyException
@throws IOException


public void load(String className) throws PropertyException, IOException
   {
      if (className == null)
         throw new NullArgumentException("className");

      PropertyReader reader = null;

      try
      {
         Class type = Class.forName(className);
         reader = (PropertyReader) type.newInstance();
      }
      catch (Exception e)
      {
         throw new PropertyException(e);
      }

      // load the properties from the source
      load(reader);
   }

public
void
load
(
String
className
)
throws
PropertyException
,
IOException
{
if
(
className
==
)
throw
new
NullArgumentException
(
"className"
)
;
PropertyReader
reader
=
;
try
{
Class
type
=
Class
.
forName
(
className
)
;
reader
=
(
PropertyReader
)
type
.
newInstance
(
)
;
}
catch
(
Exception
e
)
{
throw
new
PropertyException
(
e
)
;
}
// load the properties from the source
load
(
reader
)
;
}

Load properties from a PropertyReader specifed by the given class name.

@param className     Class name of a PropertyReader to read from.
@throws PropertyException
@throws IOException

Load properties from a PropertyReader specifed by the given class name .


public PropertyGroup getPropertyGroup(String basename, int index)
   {
      String name = makeIndexPropertyName(basename, index);
      return getPropertyGroup(name);
   }

public PropertyGroup getPropertyGroup ( String basename , int index ) { String name = makeIndexPropertyName ( basename , index ) ; return getPropertyGroup ( name ) ; }

Get a property group for the given property base at the given index.

@param basename   Base property name.
@param index      Array property index.
@return           Property group.

Get a property group for the given property base at the given index .


public boolean isEntityResolved()
   {
       Boolean value = entityResolved.get();
       return value != null ? value.booleanValue() : false;
   }

public boolean isEntityResolved ( ) { Boolean value = entityResolved . get ( ) ; return value != null ? value . booleanValue ( ) : false ; }

Returns the boolean value to inform id DTD was found in the XML file or not

@return boolean - true if DTD was found in XML


protected InputSource resolveSystemID(String systemId, boolean trace)
   {
      if( systemId == null )
         return null;

      if( trace )
         log.trace("resolveSystemID, systemId="+systemId);

      InputSource inputSource = null;

      // Try to resolve the systemId as an entity key
      String filename = null;
      if( localEntities != null )
         filename = (String) localEntities.get(systemId);
      if( filename == null )
         filename = (String) entities.get(systemId);

      if ( filename != null )
      {
         if( trace )
            log.trace("Found entity systemId=" + systemId + " fileName=" + filename);

         InputStream ins = loadClasspathResource(filename, trace);
         if( ins != null )
         {
            inputSource = new InputSource(ins);
            inputSource.setSystemId(systemId);
         }
         else
         {
            log.warn("Cannot load systemId from resource: " + filename);
         }
      }

      return inputSource;
   }

Attempt to use the systemId as a URL from which the schema can be read. This
checks to see whether the systemId is a key to an entry in the class
entity map.

@param systemId - the systemId
@param trace - trace level logging flag
@return the URL InputSource if the URL input stream can be opened, null
if the systemId is not a URL or could not be opened.

Attempt to use the systemId as a URL from which the schema can be read . This checks to see whether the systemId is a key to an entry in the class entity map .


protected InputSource resolveSystemIDasURL(String systemId, boolean trace)
  {
     if( systemId == null )
        return null;

     if( trace )
        log.trace("resolveSystemIDasURL, systemId="+systemId);

     InputSource inputSource = null;

     // Try to use the systemId as a URL to the schema
      try
      {
         if (trace)
            log.trace("Trying to resolve systemId as a URL");
         // Replace any system property refs if isReplaceSystemProperties is true
         if(isReplaceSystemProperties())
            systemId = StringPropertyReplacer.replaceProperties(systemId);
         URL url = new URL(systemId);
         if (warnOnNonFileURLs
             && url.getProtocol().equalsIgnoreCase("file") == false
             && url.getProtocol().equalsIgnoreCase("vfszip") == false)
         {
            log.warn("Trying to resolve systemId as a non-file URL: " + systemId);
         }

         InputStream ins = url.openStream();
         if (ins != null)
         {
            inputSource = new InputSource(ins);
            inputSource.setSystemId(systemId);
         }
         else
         {
            log.warn("Cannot load systemId as URL: " + systemId);
         }

         if (trace)
            log.trace("Resolved systemId as a URL");
      }
      catch (MalformedURLException ignored)
      {
         if (trace)
            log.trace("SystemId is not a url: " + systemId, ignored);
      }
      catch (IOException e)
      {
         if (trace)
            log.trace("Failed to obtain URL.InputStream from systemId: " + systemId, e);
      }
      return inputSource;
  }

Attempt to use the systemId as a URL from which the schema can be read. This
uses the systemID as a URL.

@param systemId - the systemId
@param trace - trace level logging flag
@return the URL InputSource if the URL input stream can be opened, null
if the systemId is not a URL or could not be opened.

Attempt to use the systemId as a URL from which the schema can be read . This uses the systemID as a URL .


protected InputSource resolveClasspathName(String systemId, boolean trace)
   {
      if( systemId == null )
         return null;

      if( trace )
         log.trace("resolveClasspathName, systemId="+systemId);
      String filename = systemId;
      // Parse the systemId as a uri to get the final path component
      try
      {
         URI url = new URI(systemId);
         String path = url.getPath();
         if( path == null )
            path = url.getSchemeSpecificPart();
         int slash = path.lastIndexOf('/');
         if( slash >= 0 )
            filename = path.substring(slash + 1);
         else
            filename = path;

         if(filename.length() == 0)
            return null;

         if (trace)
            log.trace("Mapped systemId to filename: " + filename);
      }
      catch (URISyntaxException e)
      {
         if (trace)
            log.trace("systemId: is not a URI, using systemId as resource", e);
      }

      // Resolve the filename as a classpath resource
      InputStream is = loadClasspathResource(filename, trace);
      InputSource inputSource = null;
      if( is != null )
      {
         inputSource = new InputSource(is);
         inputSource.setSystemId(systemId);
      }
      return inputSource;
   }

Resolve the systemId as a classpath resource. If not found, the
systemId is simply used as a classpath resource name.

@param systemId - the system ID of DTD or Schema
@param trace - trace level logging flag
@return the InputSource for the schema file found on the classpath, null
if the systemId is not registered or found.

Resolve the systemId as a classpath resource . If not found the systemId is simply used as a classpath resource name .


public void setAsText(String text)
   {
      Document d = getAsDocument(text);
      setValue(d.getDocumentElement());
   }

public void setAsText ( String text ) { Document d = getAsDocument ( text ) ; setValue ( d . getDocumentElement ( ) ) ; }

Sets as an Element created by a String .


public static String normalize(String publicId) {
    String normal = publicId.replace('\t', ' ');
    normal = normal.replace('\r', ' ');
    normal = normal.replace('\n', ' ');
    normal = normal.trim();

    int pos;

    while ((pos = normal.indexOf("  ")) >= 0) {
      normal = normal.substring(0, pos) + normal.substring(pos+1);
    }

    return normal;
  }

public
static
String
normalize
(
String
publicId
)
{
String
normal
=
publicId
.
replace
(
'
'
,
'
'
)
;
normal
=
normal
.
replace
(
'
'
,
'
'
)
;
normal
=
normal
.
replace
(
'
'
,
'
'
)
;
normal
=
normal
.
trim
(
)
;
int
pos
;
while
(
(
pos
=
normal
.
indexOf
(
"  "
)
)
>=
0
)
{
normal
=
normal
.
substring
(
0
,
pos
)
+
normal
.
substring
(
pos
+
1
)
;
}
return
normal
;
}

Normalize a public identifier.

Public identifiers must be normalized according to the following
rules before comparisons between them can be made:

Whitespace characters are normalized to spaces (e.g., line feeds,
tabs, etc. become spaces).

Leading and trailing whitespace is removed.

Multiple internal whitespaces are normalized to a single
space.

This method is declared static so that other classes
can use it directly.

@param publicId The unnormalized public identifier.

@return The normalized identifier.


public static String encodeURN(String publicId) {
    String urn = PublicId.normalize(publicId);

    urn = PublicId.stringReplace(urn, "%", "%25");
    urn = PublicId.stringReplace(urn, ";", "%3B");
    urn = PublicId.stringReplace(urn, "'", "%27");
    urn = PublicId.stringReplace(urn, "?", "%3F");
    urn = PublicId.stringReplace(urn, "#", "%23");
    urn = PublicId.stringReplace(urn, "+", "%2B");
    urn = PublicId.stringReplace(urn, " ", "+");
    urn = PublicId.stringReplace(urn, "::", ";");
    urn = PublicId.stringReplace(urn, ":", "%3A");
    urn = PublicId.stringReplace(urn, "//", ":");
    urn = PublicId.stringReplace(urn, "/", "%2F");

    return "urn:publicid:" + urn;
  }

public
static
String
encodeURN
(
String
publicId
)
{
String
urn
=
PublicId
.
normalize
(
publicId
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"%"
,
"%25"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
";"
,
"%3B"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"'"
,
"%27"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"?"
,
"%3F"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"#"
,
"%23"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"+"
,
"%2B"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
" "
,
"+"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"::"
,
";"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
":"
,
"%3A"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"//"
,
":"
)
;
urn
=
PublicId
.
stringReplace
(
urn
,
"/"
,
"%2F"
)
;
return
"urn:publicid:"
+
urn
;
}

Encode a public identifier as a "publicid" URN.

This method is declared static so that other classes
can use it directly.

@param publicId The unnormalized public identifier.

@return The normalized identifier.

Encode a public identifier as a publicid URN .


public static String decodeURN(String urn) {
    String publicId = "";

    if (urn.startsWith("urn:publicid:")) {
      publicId = urn.substring(13);
    } else {
      return urn;
    }

    publicId = PublicId.stringReplace(publicId, "%2F", "/");
    publicId = PublicId.stringReplace(publicId, ":", "//");
    publicId = PublicId.stringReplace(publicId, "%3A", ":");
    publicId = PublicId.stringReplace(publicId, ";", "::");
    publicId = PublicId.stringReplace(publicId, "+", " ");
    publicId = PublicId.stringReplace(publicId, "%2B", "+");
    publicId = PublicId.stringReplace(publicId, "%23", "#");
    publicId = PublicId.stringReplace(publicId, "%3F", "?");
    publicId = PublicId.stringReplace(publicId, "%27", "'");
    publicId = PublicId.stringReplace(publicId, "%3B", ";");
    publicId = PublicId.stringReplace(publicId, "%25", "%");

    return publicId;
    }

public
static
String
decodeURN
(
String
urn
)
{
String
publicId
=
""
;
if
(
urn
.
startsWith
(
"urn:publicid:"
)
)
{
publicId
=
urn
.
substring
(
13
)
;
}
else
{
return
urn
;
}
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%2F"
,
"/"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
":"
,
"//"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%3A"
,
":"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
";"
,
"::"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"+"
,
" "
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%2B"
,
"+"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%23"
,
"#"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%3F"
,
"?"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%27"
,
"'"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%3B"
,
";"
)
;
publicId
=
PublicId
.
stringReplace
(
publicId
,
"%25"
,
"%"
)
;
return
publicId
;
}

Decode a "publicid" URN into a public identifier.

This method is declared static so that other classes
can use it directly.

@param urn The unnormalized public identifier.

@return The normalized identifier.

Decode a publicid URN into a public identifier .


private static String stringReplace(String str,
				      String oldStr,
				      String newStr) {

    String result = "";
    int pos = str.indexOf(oldStr);

    //    System.out.println(str + ": " + oldStr + " => " + newStr);

    while (pos >= 0) {
      //      System.out.println(str + " (" + pos + ")");
      result += str.substring(0, pos);
      result += newStr;
      str = str.substring(pos+1);

      pos = str.indexOf(oldStr);
    }

    return result + str;
  }


public void start(final boolean reset)
   {
      if (!running) {
         if (reset) reset();
         start = System.currentTimeMillis();
         running = true;
      }
   }

public void start ( final boolean reset ) { if ( ! running ) { if ( reset ) reset ( ) ; start = System . currentTimeMillis ( ) ; running = true ; } }

Start the watch.

@param reset   True to reset the watch prior to starting.


public long stop()
   {
      long lap = 0;

      if (running) {
         count++;
         stop = System.currentTimeMillis();
         lap = stop - start;
         total += lap;
         running = false;
      }

      return lap;
   }

public long stop ( ) { long lap = 0 ; if ( running ) { count ++ ; stop = System . currentTimeMillis ( ) ; lap = stop - start ; total += lap ; running = false ; } return lap ; }

Stop the watch.

@return  Elapsed time or 0 if the watch was never started.


public static StopWatch makeSynchronized(final StopWatch watch)
   {
      return new Wrapper(watch)
         {
         /** The serialVersionUID */
         private static final long serialVersionUID = -6284244000894114817L;
            public synchronized void start(final boolean reset) {
               this.watch.start(reset);
            }

            public synchronized void start() {
               this.watch.start();
            }

            public synchronized long stop() {
               return this.watch.stop();
            }

            public synchronized void reset() {
               this.watch.reset();
            }

            public synchronized long getLapTime() {
               return this.watch.getLapTime();
            }

            public synchronized long getAverageLapTime() {
               return this.watch.getAverageLapTime();
            }

            public synchronized int getLapCount() {
               return this.watch.getLapCount();
            }

            public synchronized long getTime() {
               return this.watch.getTime();
            }

            public synchronized boolean isRunning() {
               return this.watch.isRunning();
            }

            public synchronized String toString() {
               return this.watch.toString();
            }
         };
   }

public
static
StopWatch
makeSynchronized
(
final
StopWatch
watch
)
{
return
new
Wrapper
(
watch
)
{
/** The serialVersionUID */
private
static
final
long
serialVersionUID
=
6284244000894114817L
;
public
synchronized
void
start
(
final
boolean
reset
)
{
this
.
watch
.
start
(
reset
)
;
}
public
synchronized
void
start
(
)
{
this
.
watch
.
start
(
)
;
}
public
synchronized
long
stop
(
)
{
return
this
.
watch
.
stop
(
)
;
}
public
synchronized
void
reset
(
)
{
this
.
watch
.
reset
(
)
;
}
public
synchronized
long
getLapTime
(
)
{
return
this
.
watch
.
getLapTime
(
)
;
}
public
synchronized
long
getAverageLapTime
(
)
{
return
this
.
watch
.
getAverageLapTime
(
)
;
}
public
synchronized
int
getLapCount
(
)
{
return
this
.
watch
.
getLapCount
(
)
;
}
public
synchronized
long
getTime
(
)
{
return
this
.
watch
.
getTime
(
)
;
}
public
synchronized
boolean
isRunning
(
)
{
return
this
.
watch
.
isRunning
(
)
;
}
public
synchronized
String
toString
(
)
{
return
this
.
watch
.
toString
(
)
;
}
}
;
}

Return a synchronized stop watch.

@param watch    StopWatch to synchronize.
@return         Synchronized stop watch.


public int compareTo(final Object obj) throws ClassCastException {
      HashCode hashCode = (HashCode)obj;
      return compareTo(hashCode.value);
   }

public int compareTo ( final Object obj ) throws ClassCastException { HashCode hashCode = ( HashCode ) obj ; return compareTo ( hashCode . value ) ; }

Compares this object with the specified object for order.

@param obj   Value to compare with.
@return        A negative integer, zero, or a positive integer as
this object is less than, equal to, or greater than
the specified object.

@throws ClassCastException    Object is not a <tt>HashCode</tt>.

Compares this object with the specified object for order .


public static int generate(final byte[] bytes) {
      int hashcode = 0;

      for (int i=0; i<bytes.length; i++) {
         hashcode <<= 1;
         hashcode ^= bytes[i];
      }

      return hashcode;
   }

public static int generate ( final byte [ ] bytes ) { int hashcode = 0 ; for ( int i = 0 ; i < bytes . length ; i ++ ) { hashcode <<= 1 ; hashcode ^= bytes [ i ] ; } return hashcode ; }

Generate a hash code for a byte array.

@param bytes   An array of bytes to generate a hash code from.
@return        Hash code.


public static int generate(final Object array[], final boolean deep) {
      int hashcode = 0;

      for (int i=0; i<array.length; i++) {
         if (deep && (array[i] instanceof Object[])) {
            hashcode ^= generate((Object[])array[i], true);
         }
         else {
            hashcode ^= array[i].hashCode();
         }
      }

      return hashcode;
   }

public static int generate ( final Object array [ ] , final boolean deep ) { int hashcode = 0 ; for ( int i = 0 ; i < array . length ; i ++ ) { if ( deep && ( array [ i ] instanceof Object [ ] ) ) { hashcode ^= generate ( ( Object [ ] ) array [ i ] , true ) ; } else { hashcode ^= array [ i ] . hashCode ( ) ; } } return hashcode ; }

Generate a hash code for an object array.

<p>Does not handle nested primitive array elements.

@param array   Array to generate hashcode for.
@param deep    True to traverse elements which are arrays to
determine the elements hash code.
@return        Hash code.

Generate a hash code for an object array .


public void create()
   {
      m_map = createMap();
      m_list = createList();
      m_list.m_maxCapacity = m_maxCapacity;
      m_list.m_minCapacity = m_minCapacity;
      m_list.m_capacity = m_maxCapacity;
   }

public void create ( ) { m_map = createMap ( ) ; m_list = createList ( ) ; m_list . m_maxCapacity = m_maxCapacity ; m_list . m_minCapacity = m_minCapacity ; m_list . m_capacity = m_maxCapacity ; }

Initializes the cache, creating all required objects and initializing their
values.
@see #start
@see #destroy

Initializes the cache creating all required objects and initializing their values .


protected void setFieldValue(String value) {
      try {
         // filter property value
         value = filterValue(value);

         // coerce value to field type
         Class<?> type = fieldInstance.getField().getType();
         PropertyEditor editor = PropertyEditors.findEditor(type);
         editor.setAsText(value);
         Object coerced = editor.getValue();

         // bind value to field
         fieldInstance.set(coerced);
      }
      catch (IllegalAccessException e) {
         throw new PropertyException(e);
      }
   }

protected
void
setFieldValue
(
String
value
)
{
try
{
// filter property value
value
=
filterValue
(
value
)
;
// coerce value to field type
Class
<
>
type
=
fieldInstance
.
getField
(
)
.
getType
(
)
;
PropertyEditor
editor
=
PropertyEditors
.
findEditor
(
type
)
;
editor
.
setAsText
(
value
)
;
Object
coerced
=
editor
.
getValue
(
)
;
// bind value to field
fieldInstance
.
set
(
coerced
)
;
}
catch
(
IllegalAccessException
e
)
{
throw
new
PropertyException
(
e
)
;
}
}

Coerce and set specified value to field.

@param value   Field value.

@throws PropertyException     Failed to set field value.

Coerce and set specified value to field .


protected String nextToken() throws IOException {
    String token = "";
    int ch, nextch;

    if (!tokenStack.empty()) {
      return (String) tokenStack.pop();
    }

    // Skip over leading whitespace and comments
    while (true) {
      // skip leading whitespace
      ch = catfile.read();
      while (ch <= ' ') {      // all ctrls are whitespace
	ch = catfile.read();
	if (ch < 0) {
	  return null;
	}
      }

      // now 'ch' is the current char from the file
      nextch = catfile.read();
      if (nextch < 0) {
	return null;
      }

      if (ch == '-' && nextch == '-') {
	// we've found a comment, skip it...
	ch = ' ';
	nextch = nextChar();
	while (ch != '-' || nextch != '-') {
	  ch = nextch;
	  nextch = nextChar();
	}

	// Ok, we've found the end of the comment,
	// loop back to the top and start again...
      } else {
	stack[++top] = nextch;
	stack[++top] = ch;
	break;
      }
    }

    ch = nextChar();
    if (ch == '"' || ch == '\'') {
      int quote = ch;
      while ((ch = nextChar()) != quote) {
	char[] chararr = new char[1];
	chararr[0] = (char) ch;
	String s = new String(chararr);
	token = token.concat(s);
      }
      return token;
    } else {
      // return the next whitespace or comment delimited
      // string
      while (ch > ' ') {
	nextch = nextChar();
	if (ch == '-' && nextch == '-') {
	  stack[++top] = ch;
	  stack[++top] = nextch;
	  return token;
	} else {
	  char[] chararr = new char[1];
	  chararr[0] = (char) ch;
	  String s = new String(chararr);
	  token = token.concat(s);
	  ch = nextch;
	}
      }
      return token;
    }
  }

Return the next token in the catalog file.

@return The Catalog file token from the input stream.
@throws IOException If an error occurs reading from the stream.

Return the next token in the catalog file .


public static void initialize()
   {
      PrivilegedAction action = new PrivilegedAction()
      {
         public Object run()
         {
            String defaultFormat = System.getProperty("org.jboss.util.propertyeditor.DateEditor.format", "MMM d, yyyy");
            String defaultLocale = System.getProperty("org.jboss.util.propertyeditor.DateEditor.locale");
            DateFormat defaultDateFormat;
            if (defaultLocale == null || defaultLocale.length() == 0)
            {
               defaultDateFormat = new SimpleDateFormat(defaultFormat);
            }
            else
            {
               defaultDateFormat = new SimpleDateFormat(defaultFormat, Strings.parseLocaleString(defaultLocale));
            }

            formats = new DateFormat[]
            {
               defaultDateFormat,
               // Tue Jan 04 00:00:00 PST 2005
               new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy"),
               // Wed, 4 Jul 2001 12:08:56 -0700
               new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z")
            };
            return null;
         }
      };
      AccessController.doPrivileged(action);
   }

Setup the parsing formats. Offered as a separate static method to allow
testing of locale changes, since SimpleDateFormat will use the default
locale upon construction. Should not be normally used!

Setup the parsing formats . Offered as a separate static method to allow testing of locale changes since SimpleDateFormat will use the default locale upon construction . Should not be normally used!


public boolean addVertex(Vertex<T> v)
   {
      if( verticies.containsValue(v) == false )
      {
         verticies.put(v.getName(), v);
         return true;
      }
      return false;
   }

public boolean addVertex ( Vertex < T > v ) { if ( verticies . containsValue ( v ) == false ) { verticies . put ( v . getName ( ) , v ) ; return true ; } return false ; }

Add a vertex to the graph
@param v the Vertex to add
@return true if the vertex was added, false if it was already in the graph.


public void setRootVertex(Vertex<T> root)
   {
      this.rootVertex = root;
      if( verticies.containsValue(root) == false )
         addVertex(root);
   }

public void setRootVertex ( Vertex < T > root ) { this . rootVertex = root ; if ( verticies . containsValue ( root ) == false ) addVertex ( root ) ; }

Set a root vertex. If root does no exist in the graph it is added.
@param root - the vertex to set as the root and optionally add if it
does not exist in the graph.

Set a root vertex . If root does no exist in the graph it is added .


public boolean removeVertex(Vertex<T> v)
   {
      if (!verticies.containsValue(v))
         return false;

      verticies.remove(v.getName());
      if( v == rootVertex )
         rootVertex = null;

      // Remove the edges associated with v
      for(int n = 0; n < v.getOutgoingEdgeCount(); n ++)
      {
         Edge<T> e = v.getOutgoingEdge(n);
         v.remove(e);
         Vertex<T> to = e.getTo();
         to.remove(e);
         edges.remove(e);
      }
      for(int n = 0; n < v.getIncomingEdgeCount(); n ++)
      {
         Edge<T> e = v.getIncomingEdge(n);
         v.remove(e);
         Vertex<T> predecessor = e.getFrom();
         predecessor.remove(e);
      }
      return true;
   }

public
boolean
removeVertex
(
Vertex
<
T
>
v
)
{
if
(
!
verticies
.
containsValue
(
v
)
)
return
false
;
verticies
.
remove
(
v
.
getName
(
)
)
;
if
(
v
==
rootVertex
)
rootVertex
=
;
// Remove the edges associated with v
for
(
int
n
=
0
;
n
<
v
.
getOutgoingEdgeCount
(
)
;
n
++
)
{
Edge
<
T
>
e
=
v
.
getOutgoingEdge
(
n
)
;
v
.
remove
(
e
)
;
Vertex
<
T
>
to
=
e
.
getTo
(
)
;
to
.
remove
(
e
)
;
edges
.
remove
(
e
)
;
}
for
(
int
n
=
0
;
n
<
v
.
getIncomingEdgeCount
(
)
;
n
++
)
{
Edge
<
T
>
e
=
v
.
getIncomingEdge
(
n
)
;
v
.
remove
(
e
)
;
Vertex
<
T
>
predecessor
=
e
.
getFrom
(
)
;
predecessor
.
remove
(
e
)
;
}
return
true
;
}

Remove a vertex from the graph
@param v the Vertex to remove
@return true if the Vertex was removed


public void depthFirstSearch(Vertex<T> v, final Visitor<T> visitor)
   {
      VisitorEX<T, RuntimeException> wrapper = new VisitorEX<T, RuntimeException>()
      {
         public void visit(Graph<T> g, Vertex<T> v) throws RuntimeException
         {
            if (visitor != null)
               visitor.visit(g, v);
         }
      };
      this.depthFirstSearch(v, wrapper);
   }

public void depthFirstSearch ( Vertex < T > v , final Visitor < T > visitor ) { VisitorEX < T , RuntimeException > wrapper = new VisitorEX < T , RuntimeException > ( ) { public void visit ( Graph < T > g , Vertex < T > v ) throws RuntimeException { if ( visitor != null ) visitor . visit ( g , v ) ; } } ; this . depthFirstSearch ( v , wrapper ) ; }

Perform a depth first serach using recursion.
@param v - the Vertex to start the search from
@param visitor - the vistor to inform prior to
@see Visitor#visit(Graph, Vertex)

Perform a depth first serach using recursion .


public void dfsSpanningTree(Vertex<T> v, DFSVisitor<T> visitor)
   {
      v.visit();
      if( visitor != null )
         visitor.visit(this, v);

      for (int i = 0; i < v.getOutgoingEdgeCount(); i++)
      {
         Edge<T> e = v.getOutgoingEdge(i);
         if (!e.getTo().visited())
         {
            if( visitor != null )
               visitor.visit(this, v, e);
            e.mark();
            dfsSpanningTree(e.getTo(), visitor);
         }
      }
   }

public void dfsSpanningTree ( Vertex < T > v , DFSVisitor < T > visitor ) { v . visit ( ) ; if ( visitor != null ) visitor . visit ( this , v ) ; for ( int i = 0 ; i < v . getOutgoingEdgeCount ( ) ; i ++ ) { Edge < T > e = v . getOutgoingEdge ( i ) ; if ( ! e . getTo ( ) . visited ( ) ) { if ( visitor != null ) visitor . visit ( this , v , e ) ; e . mark ( ) ; dfsSpanningTree ( e . getTo ( ) , visitor ) ; } } }

Find the spanning tree using a DFS starting from v.
@param v - the vertex to start the search from
@param visitor - visitor invoked after each vertex
is visited and an edge is added to the tree.

Find the spanning tree using a DFS starting from v .


public Vertex<T> findVertexByData(T data, Comparator<T> compare)
   {
      Vertex<T> match = null;
      for(Vertex<T> v : verticies.values())
      {
         if( compare.compare(data, v.getData()) == 0 )
         {
            match = v;
            break;
         }
      }
      return match;
   }

public Vertex < T > findVertexByData ( T data , Comparator < T > compare ) { Vertex < T > match = null ; for ( Vertex < T > v : verticies . values ( ) ) { if ( compare . compare ( data , v . getData ( ) ) == 0 ) { match = v ; break ; } } return match ; }

Search the verticies for one with data.

@param data - the vertex data to match
@param compare - the comparator to perform the match
@return the first vertex with a matching data, null if no
matches are found

Search the verticies for one with data .


public Edge<T>[] findCycles()
   {
      ArrayList<Edge<T>> cycleEdges = new ArrayList<Edge<T>>();
      // Mark all verticies as white
      for(int n = 0; n < verticies.size(); n ++)
      {
         Vertex<T> v = getVertex(n);
         v.setMarkState(VISIT_COLOR_WHITE);
      }
      for(int n = 0; n < verticies.size(); n ++)
      {
         Vertex<T> v = getVertex(n);
         visit(v, cycleEdges);
      }

      Edge<T>[] cycles = new Edge[cycleEdges.size()];
      cycleEdges.toArray(cycles);
      return cycles;
   }

public
Edge
<
T
>
[
]
findCycles
(
)
{
ArrayList
<
Edge
<
T
>>
cycleEdges
=
new
ArrayList
<
Edge
<
T
>
>
(
)
;
// Mark all verticies as white
for
(
int
n
=
0
;
n
<
verticies
.
size
(
)
;
n
++
)
{
Vertex
<
T
>
v
=
getVertex
(
n
)
;
v
.
setMarkState
(
VISIT_COLOR_WHITE
)
;
}
for
(
int
n
=
0
;
n
<
verticies
.
size
(
)
;
n
++
)
{
Vertex
<
T
>
v
=
getVertex
(
n
)
;
visit
(
v
,
cycleEdges
)
;
}
Edge
<
T
>
[
]
cycles
=
new
Edge
[
cycleEdges
.
size
(
)
]
;
cycleEdges
.
toArray
(
cycles
)
;
return
cycles
;
}

Search the graph for cycles. In order to detect cycles, we use
a modified depth first search called a colored DFS. All nodes are
initially marked white. When a node is encountered, it is marked
grey, and when its descendants are completely visited, it is
marked black. If a grey node is ever encountered, then there is
a cycle.
@return the edges that form cycles in the graph. The array will
be empty if there are no cycles.

Search the graph for cycles . In order to detect cycles we use a modified depth first search called a colored DFS . All nodes are initially marked white . When a node is encountered it is marked grey and when its descendants are completely visited it is marked black . If a grey node is ever encountered then there is a cycle .


public static String normalize(String s, boolean canonical)
   {
      StringBuffer str = new StringBuffer();

      int len = (s != null) ? s.length() : 0;
      for (int i = 0; i < len; i++)
      {
         char ch = s.charAt(i);
         switch (ch)
         {
            case '<':
            {
               str.append("<");
               break;
            }
            case '>':
            {
               str.append(">");
               break;
            }
            case '&':
            {
               str.append("&");
               break;
            }
            case '"':
            {
               str.append(""");
               break;
            }
            case '\'':
            {
               str.append("'");
               break;
            }
            case '\r':
            case '\n':
            {
               if (canonical)
               {
                  str.append("&#");
                  str.append(Integer.toString(ch));
                  str.append(';');
                  break;
               }
               // else, default append char
            }
            default:
            {
               str.append(ch);
            }
         }
      }
      return (str.toString());
   }

public
static
String
normalize
(
String
s
,
boolean
canonical
)
{
StringBuffer
str
=
new
StringBuffer
(
)
;
int
len
=
(
s
!=
)
s
.
length
(
)
:
0
;
for
(
int
i
=
0
;
i
<
len
;
i
++
)
{
char
ch
=
s
.
charAt
(
i
)
;
switch
(
ch
)
{
case
'
'
:
{
str
.
append
(
"<"
)
;
break
;
}
case
'
'
:
{
str
.
append
(
">"
)
;
break
;
}
case
'
'
:
{
str
.
append
(
"&"
)
;
break
;
}
case
'
'
:
{
str
.
append
(
"""
)
;
break
;
}
case
'
'
:
{
str
.
append
(
"'"
)
;
break
;
}
case
'
'
:
case
'
'
:
{
if
(
canonical
)
{
str
.
append
(
"&#"
)
;
str
.
append
(
Integer
.
toString
(
ch
)
)
;
str
.
append
(
'
'
)
;
break
;
}
// else, default append char
}
default
:
{
str
.
append
(
ch
)
;
}
}
}
return
(
str
.
toString
(
)
)
;
}


public static Element parse(String xmlString) throws IOException
    {
        try
        {
            return parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8")));
        }
        catch (IOException e)
        {
            log.error("Cannot parse: " + xmlString);
            throw e;
        }
    }

public
static
Element
parse
(
String
xmlString
)
throws
IOException
{
try
{
return
parse
(
new
ByteArrayInputStream
(
xmlString
.
getBytes
(
"UTF-8"
)
)
)
;
}
catch
(
IOException
e
)
{
log
.
error
(
"Cannot parse: "
+
xmlString
)
;
throw
e
;
}
}

Parse the given XML string and return the root Element
@param xmlString
@return the element
@throws IOException


public static Element parse(InputStream xmlStream) throws IOException
    {
        try
        {
            Document doc = getDocumentBuilder().parse(xmlStream);
            Element root = doc.getDocumentElement();
            return root;
        }
        catch (SAXException e)
        {
            throw new IOException(e.toString());
        }
    }

public static Element parse ( InputStream xmlStream ) throws IOException { try { Document doc = getDocumentBuilder ( ) . parse ( xmlStream ) ; Element root = doc . getDocumentElement ( ) ; return root ; } catch ( SAXException e ) { throw new IOException ( e . toString ( ) ) ; } }

Parse the given XML stream and return the root Element
@param xmlStream
@return the element
@throws IOException


public static Element parse(InputSource source) throws IOException
    {
        try
        {
            Document doc = getDocumentBuilder().parse(source);
            Element root = doc.getDocumentElement();
            return root;
        }
        catch (SAXException e)
        {
            throw new IOException(e.toString());
        }
    }

public static Element parse ( InputSource source ) throws IOException { try { Document doc = getDocumentBuilder ( ) . parse ( source ) ; Element root = doc . getDocumentElement ( ) ; return root ; } catch ( SAXException e ) { throw new IOException ( e . toString ( ) ) ; } }

Parse the given input source and return the root Element
@param source
@return the element
@throws IOException


public static Element createElement(String localPart)
    {
        Document doc = getOwnerDocument();
        log.trace("createElement {}" + localPart);
        return doc.createElement(localPart);
    }

public
static
Element
createElement
(
String
localPart
)
{
Document
doc
=
getOwnerDocument
(
)
;
log
.
trace
(
"createElement {}"
+
localPart
)
;
return
doc
.
createElement
(
localPart
)
;
}

Create an Element for a given name
@param localPart
@return the element


public static QName resolveQName(Element el, String qualifiedName)
    {
        QName qname;
        String prefix = "";
        String namespaceURI = "";
        String localPart = qualifiedName;

        int colIndex = qualifiedName.indexOf(":");
        if (colIndex > 0)
        {
            prefix = qualifiedName.substring(0, colIndex);
            localPart = qualifiedName.substring(colIndex + 1);

            if ("xmlns".equals(prefix))
            {
                namespaceURI = "URI:XML_PREDEFINED_NAMESPACE";
            }
            else
            {
                Element nsElement = el;
                while (namespaceURI.equals("") && nsElement != null)
                {
                    namespaceURI = nsElement.getAttribute("xmlns:" + prefix);
                    if (namespaceURI.equals(""))
                        nsElement = getParentElement(nsElement);
                }
            }

            if (namespaceURI.equals(""))
                throw new IllegalArgumentException("Cannot find namespace uri for: " + qualifiedName);
        }

        qname = new QName(namespaceURI, localPart, prefix);
        return qname;
    }

public
static
QName
resolveQName
(
Element
el
,
String
qualifiedName
)
{
QName
qname
;
String
prefix
=
""
;
String
namespaceURI
=
""
;
String
localPart
=
qualifiedName
;
int
colIndex
=
qualifiedName
.
indexOf
(
":"
)
;
if
(
colIndex
>
0
)
{
prefix
=
qualifiedName
.
substring
(
0
,
colIndex
)
;
localPart
=
qualifiedName
.
substring
(
colIndex
+
1
)
;
if
(
"xmlns"
.
equals
(
prefix
)
)
{
namespaceURI
=
"URI:XML_PREDEFINED_NAMESPACE"
;
}
else
{
Element
nsElement
=
el
;
while
(
namespaceURI
.
equals
(
""
)
&&
nsElement
!=
)
{
namespaceURI
=
nsElement
.
getAttribute
(
"xmlns:"
+
prefix
)
;
if
(
namespaceURI
.
equals
(
""
)
)
nsElement
=
getParentElement
(
nsElement
)
;
}
}
if
(
namespaceURI
.
equals
(
""
)
)
throw
new
IllegalArgumentException
(
"Cannot find namespace uri for: "
+
qualifiedName
)
;
}
qname
=
new
QName
(
namespaceURI
,
localPart
,
prefix
)
;
return
qname
;
}

Transform the giveen qualified name into a QName
@param el
@param qualifiedName
@return the resolved name


public static void copyAttributes(Element destElement, Element srcElement)
    {
        NamedNodeMap attribs = srcElement.getAttributes();
        for (int i = 0; i < attribs.getLength(); i++)
        {
            Attr attr = (Attr)attribs.item(i);
            String uri = attr.getNamespaceURI();
            String qname = attr.getName();
            String value = attr.getNodeValue();

            // Prevent DOMException: NAMESPACE_ERR: An attempt is made to create or
            // change an object in a way which is incorrect with regard to namespaces.
            if (uri == null && qname.startsWith("xmlns"))
            {
               log.trace("Ignore attribute: [uri=" + uri + ",qname=" + qname + ",value=" + value + "]");
            }
            else
            {
               destElement.setAttributeNS(uri, qname, value);
            }
        }
    }

Copy attributes between elements
@param destElement
@param srcElement


public static boolean hasChildElements(Node node)
    {
        NodeList nlist = node.getChildNodes();
        for (int i = 0; i < nlist.getLength(); i++)
        {
            Node child = nlist.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE)
                return true;
        }
        return false;
    }

public static boolean hasChildElements ( Node node ) { NodeList nlist = node . getChildNodes ( ) ; for ( int i = 0 ; i < nlist . getLength ( ) ; i ++ ) { Node child = nlist . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) return true ; } return false ; }

True if the node has child elements
@param node
@return true when has child elements


public static Iterator getChildElements(Node node)
    {
        ArrayList list = new ArrayList();
        NodeList nlist = node.getChildNodes();
        for (int i = 0; i < nlist.getLength(); i++)
        {
            Node child = nlist.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE)
                list.add(child);
        }
        return list.iterator();
    }

public static Iterator getChildElements ( Node node ) { ArrayList list = new ArrayList ( ) ; NodeList nlist = node . getChildNodes ( ) ; for ( int i = 0 ; i < nlist . getLength ( ) ; i ++ ) { Node child = nlist . item ( i ) ; if ( child . getNodeType ( ) == Node . ELEMENT_NODE ) list . add ( child ) ; } return list . iterator ( ) ; }

Gets child elements
@param node
@return the iterator


public static String getTextContent(Node node, boolean replaceProps)
    {
        boolean hasTextContent = false;
        StringBuffer buffer = new StringBuffer();
        NodeList nlist = node.getChildNodes();
        for (int i = 0; i < nlist.getLength(); i++)
        {
            Node child = nlist.item(i);
            if (child.getNodeType() == Node.TEXT_NODE)
            {
                buffer.append(child.getNodeValue());
                hasTextContent = true;
            }
        }
        String text = (hasTextContent ? buffer.toString() : null);
        if ( text != null && replaceProps)
           text = StringPropertyReplacer.replaceProperties(text);

        return text;
    }

public static String getTextContent ( Node node , boolean replaceProps ) { boolean hasTextContent = false ; StringBuffer buffer = new StringBuffer ( ) ; NodeList nlist = node . getChildNodes ( ) ; for ( int i = 0 ; i < nlist . getLength ( ) ; i ++ ) { Node child = nlist . item ( i ) ; if ( child . getNodeType ( ) == Node . TEXT_NODE ) { buffer . append ( child . getNodeValue ( ) ) ; hasTextContent = true ; } } String text = ( hasTextContent ? buffer . toString ( ) : null ) ; if ( text != null && replaceProps ) text = StringPropertyReplacer . replaceProperties ( text ) ; return text ; }

Get the concatenated text content, or null.
@param node node to search for TEXT_NODE conent
@param replaceProps flag indicating if ${x} property refs should be replace
@return the text content

Get the concatenated text content or null .


public static Iterator getChildElements(Node node, String nodeName)
    {
        return getChildElementsIntern(node, new QName(nodeName));
    }

public static Iterator getChildElements ( Node node , String nodeName ) { return getChildElementsIntern ( node , new QName ( nodeName ) ) ; }

Gets the child elements for a given local name without namespace
@param node
@param nodeName
@return the iterator


public static Element getParentElement(Node node)
    {
        Node parent = node.getParentNode();
        return (parent instanceof Element ? (Element)parent : null);
    }

public static Element getParentElement ( Node node ) { Node parent = node . getParentNode ( ) ; return ( parent instanceof Element ? ( Element ) parent : null ) ; }

Gets parent element or null if there is none
@param node
@return the element


public void addWaiting(Object holder, Resource resource)
   {
      synchronized (waiting)
      {
         waiting.put(holder, resource);
      }
   }

public void addWaiting ( Object holder , Resource resource ) { synchronized ( waiting ) { waiting . put ( holder , resource ) ; } }

Add a transaction waiting for a lock
@param holder
@param resource


public void readCatalog(Catalog catalog, InputStream is)
    throws IOException, CatalogException {

    DocumentBuilderFactory factory = null;
    DocumentBuilder builder = null;

    factory = DocumentBuilderFactory.newInstance();
    factory.setNamespaceAware(false);
    factory.setValidating(false);
    try {
      builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException pce) {
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    Document doc = null;

    try {
      doc = builder.parse(is);
    } catch (SAXException se) {
      throw new CatalogException(CatalogException.UNKNOWN_FORMAT);
    }

    Element root = doc.getDocumentElement();

    String namespaceURI = Namespaces.getNamespaceURI(root);
    String localName    = Namespaces.getLocalName(root);

    String domParserClass = getCatalogParser(namespaceURI,
					     localName);

    if (domParserClass == null) {
      if (namespaceURI == null) {
	catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
						  + localName);
      } else {
	catalog.getCatalogManager().debug.message(1, "No Catalog parser for "
						  + "{" + namespaceURI + "}"
						  + localName);
      }
      return;
    }

    DOMCatalogParser domParser = null;

    try {
      domParser = (DOMCatalogParser) Class.forName(domParserClass).newInstance();
    } catch (ClassNotFoundException cnfe) {
      catalog.getCatalogManager().debug.message(1, "Cannot load XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (InstantiationException ie) {
      catalog.getCatalogManager().debug.message(1, "Cannot instantiate XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (IllegalAccessException iae) {
      catalog.getCatalogManager().debug.message(1, "Cannot access XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    } catch (ClassCastException cce ) {
      catalog.getCatalogManager().debug.message(1, "Cannot cast XML Catalog Parser class", domParserClass);
      throw new CatalogException(CatalogException.UNPARSEABLE);
    }

    Node node = root.getFirstChild();
    while (node != null) {
      domParser.parseCatalogEntry(catalog, node);
      node = node.getNextSibling();
    }
  }

Read a catalog from an input stream.

This class reads a catalog from an input stream:

Based on the QName of the root element, it determines which
parser to instantiate for this catalog.

It constructs a DOM Document from the catalog and

For each child of the root node, it calls the parser's
parseCatalogEntry method. This method is expected to make
appropriate calls back into the catalog to add entries for the
entries in the catalog. It is free to do this in whatever manner
is appropriate (perhaps using just the node passed in, perhaps
wandering arbitrarily throughout the tree).

@param catalog The catalog for which this reader is called.
@param is The input stream that is to be read.
@throws IOException if the URL cannot be read.
(For example, if it is supposed to be XML and isn't well-formed or
if the parser class cannot be instantiated.)


public void readCatalog(Catalog catalog, String fileUrl)
    throws MalformedURLException, IOException, CatalogException {
    URL url = new URL(fileUrl);
    URLConnection urlCon = url.openConnection();
    readCatalog(catalog, urlCon.getInputStream());
  }

public void readCatalog ( Catalog catalog , String fileUrl ) throws MalformedURLException , IOException , CatalogException { URL url = new URL ( fileUrl ) ; URLConnection urlCon = url . openConnection ( ) ; readCatalog ( catalog , urlCon . getInputStream ( ) ) ; }

Read the catalog behind the specified URL.

@see #readCatalog(Catalog, InputStream)

@param catalog The catalog for which we are reading.
@param fileUrl The URL of the document that should be read.

@throws MalformedURLException if the specified URL cannot be
turned into a URL object.
@throws IOException if the URL cannot be read.

Read the catalog behind the specified URL .


private static byte[] getHostAddress() {
      return (byte[]) AccessController.doPrivileged(new PrivilegedAction() {
            public Object run() {
               try {
                  return InetAddress.getLocalHost().getAddress();
               }
               catch (Exception e) {
                  return UNKNOWN_HOST;
               }
            }
         });
   }

private static byte [ ] getHostAddress ( ) { return ( byte [ ] ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { try { return InetAddress . getLocalHost ( ) . getAddress ( ) ; } catch ( Exception e ) { return UNKNOWN_HOST ; } } } ) ; }

Return the current host internet address.

Return the current host internet address .


public InputSource resolveEntity(String publicId, String systemId) throws MalformedURLException, IOException
   {
      String resolvedURI = catologResolver.resolveSystem(systemId);

      if (resolvedURI == null)
      {
         resolvedURI = catologResolver.resolvePublic(publicId, systemId);
      }

      if (resolvedURI != null)
      {
         final InputSource is = new InputSource();
         is.setPublicId(publicId);
         is.setSystemId(systemId);
         is.setByteStream(this.loadResource(resolvedURI));
         this.isLastEntityResolved = true;
         return is;
      }
      else
      {
         //resource could�t be resloved
         this.isLastEntityResolved = false;
         return null;
      }
   }

public
InputSource
resolveEntity
(
String
publicId
,
String
systemId
)
throws
MalformedURLException
,
IOException
{
String
resolvedURI
=
catologResolver
.
resolveSystem
(
systemId
)
;
if
(
resolvedURI
==
)
{
resolvedURI
=
catologResolver
.
resolvePublic
(
publicId
,
systemId
)
;
}
if
(
resolvedURI
!=
)
{
final
InputSource
is
=
new
InputSource
(
)
;
is
.
setPublicId
(
publicId
)
;
is
.
setSystemId
(
systemId
)
;
is
.
setByteStream
(
this
.
loadResource
(
resolvedURI
)
)
;
this
.
isLastEntityResolved
=
true
;
return
is
;
}
else
{
//resource could�t be resloved
this
.
isLastEntityResolved
=
false
;
return
;
}
}

Tries to resolve the entity using the thread specific catolog resolvers

@param publicId - Public ID of DTD, or null if it is a schema
@param systemId - the system ID of DTD or Schema
@return InputSource of entity
@throws MalformedURLException - if the url is wrong
@throws IOException - error reading the local file


public static Throwable setSystemPropertyClassValue(String property, String className)
   {
      // Validation
      if (property == null || property.trim().length() == 0)
         throw new IllegalArgumentException("Null or empty property");
      if (className == null || className.trim().length() == 0)
         throw new IllegalArgumentException("Null or empty class name");

      // Is the class available?
      try
      {
         Thread.currentThread().getContextClassLoader().loadClass(className);
      }
      catch (Throwable problem)
      {
         return problem;
      }

      // The class is there, set the property.
      System.setProperty(property, className);
      return null;
   }

Sets the system property to a class when the class is available.

@param property the property to set
@param className the class to set as the properties value
@return any error loading the class
@exception IllegalArgumentException for a null or empty parameter

Sets the system property to a class when the class is available .


public static void displayClassInfo(Class clazz, StringBuffer results)
   {
      // Print out some codebase info for the clazz
      ClassLoader cl = clazz.getClassLoader();
      results.append("\n");
      results.append(clazz.getName());
      results.append("(");
      results.append(Integer.toHexString(clazz.hashCode()));
      results.append(").ClassLoader=");
      results.append(cl);
      ClassLoader parent = cl;
      while( parent != null )
      {
         results.append("\n..");
         results.append(parent);
         URL[] urls = getClassLoaderURLs(parent);
         int length = urls != null ? urls.length : 0;
         for(int u = 0; u < length; u ++)
         {
            results.append("\n....");
            results.append(urls[u]);
         }
         if( parent != null )
            parent = parent.getParent();
      }
      CodeSource clazzCS = clazz.getProtectionDomain().getCodeSource();
      if( clazzCS != null )
      {
         results.append("\n++++CodeSource: ");
         results.append(clazzCS);
      }
      else
         results.append("\n++++Null CodeSource");

      results.append("\nImplemented Interfaces:");
      Class[] ifaces = clazz.getInterfaces();
      for(int i = 0; i < ifaces.length; i ++)
      {
         Class iface = ifaces[i];
         results.append("\n++");
         results.append(iface);
         results.append("(");
         results.append(Integer.toHexString(iface.hashCode()));
         results.append(")");
         ClassLoader loader = ifaces[i].getClassLoader();
         results.append("\n++++ClassLoader: ");
         results.append(loader);
         ProtectionDomain pd = ifaces[i].getProtectionDomain();
         CodeSource cs = pd.getCodeSource();
         if( cs != null )
         {
            results.append("\n++++CodeSource: ");
            results.append(cs);
         }
         else
            results.append("\n++++Null CodeSource");
      }
   }

Format a string buffer containing the Class, Interfaces, CodeSource,
and ClassLoader information for the given object clazz.

@param clazz the Class
@param results - the buffer to write the info to

Format a string buffer containing the Class Interfaces CodeSource and ClassLoader information for the given object clazz .


public static void describe(StringBuffer buffer, Class clazz)
   {
      if (clazz == null)
         buffer.append("**null**");
      else
      {
         buffer.append("{class=").append(clazz.getName());
         Class[] intfs = clazz.getInterfaces();
         if (intfs.length > 0)
         {
            buffer.append(" intfs=");
            for (int i = 0; i < intfs.length; ++i)
            {
               buffer.append(intfs[i].getName());
               if (i < intfs.length-1)
                  buffer.append(", ");
            }
         }
         buffer.append("}");
      }
   }

public
static
void
describe
(
StringBuffer
buffer
,
Class
clazz
)
{
if
(
clazz
==
)
buffer
.
append
(
"**null**"
)
;
else
{
buffer
.
append
(
"{class="
)
.
append
(
clazz
.
getName
(
)
)
;
Class
[
]
intfs
=
clazz
.
getInterfaces
(
)
;
if
(
intfs
.
length
>
0
)
{
buffer
.
append
(
" intfs="
)
;
for
(
int
i
=
0
;
i
<
intfs
.
length
;
++
i
)
{
buffer
.
append
(
intfs
[
i
]
.
getName
(
)
)
;
if
(
i
<
intfs
.
length
1
)
buffer
.
append
(
", "
)
;
}
}
buffer
.
append
(
"}"
)
;
}
}

Describe the class

@param buffer the string buffer
@param clazz the clazz


public static String stripPackageName(final String classname)
   {
      int idx = classname.lastIndexOf(PACKAGE_SEPARATOR);

      if (idx != -1)
         return classname.substring(idx + 1, classname.length());
      return classname;
   }

public static String stripPackageName ( final String classname ) { int idx = classname . lastIndexOf ( PACKAGE_SEPARATOR ) ; if ( idx != - 1 ) return classname . substring ( idx + 1 , classname . length ( ) ) ; return classname ; }

Get the short name of the specified class by striping off the package
name.

@param classname  Class name.
@return           Short class name.

Get the short name of the specified class by striping off the package name .


public static String getPackageName(final String classname)
   {
      if (classname.length() == 0)
         throw new EmptyStringException();

      int index = classname.lastIndexOf(PACKAGE_SEPARATOR);
      if (index != -1)
         return classname.substring(0, index);
      return "";
   }

public static String getPackageName ( final String classname ) { if ( classname . length ( ) == 0 ) throw new EmptyStringException ( ) ; int index = classname . lastIndexOf ( PACKAGE_SEPARATOR ) ; if ( index != - 1 ) return classname . substring ( 0 , index ) ; return "" ; }

Get the package name of the specified class.

@param classname  Class name.
@return           Package name or "" if the classname is in the
<i>default</i> package.

@throws EmptyStringException     Classname is an empty string.

Get the package name of the specified class .


public static void forceLoad(final Class type)
   {
      if (type == null)
         throw new NullArgumentException("type");

      // don't attempt to force primitives to load
      if (type.isPrimitive()) return;

      // don't attempt to force java.* classes to load
      String packageName = Classes.getPackageName(type);
      // System.out.println("package name: " + packageName);

      if (packageName.startsWith("java.") ||
         packageName.startsWith("javax."))
      {
         return;
      }

      // System.out.println("forcing class to load: " + type);

      try
      {
         Method methods[] = type.getDeclaredMethods();
         Method method = null;
         for (int i = 0; i < methods.length; i++)
         {
            int modifiers = methods[i].getModifiers();
            if (Modifier.isStatic(modifiers))
            {
               method = methods[i];
               break;
            }
         }

         if (method != null)
         {
            method.invoke(null, (Object[]) null);
         }
         else
         {
            type.newInstance();
         }
      }
      catch (Exception ignore)
      {
         ThrowableHandler.add(ignore);
      }
   }

Force the given class to be loaded fully.

This method attempts to locate a static method on the given class
the attempts to invoke it with dummy arguments in the hope that
the virtual machine will prepare the class for the method call and
call all of the static class initializers.

@param type    Class to force load.

@throws NullArgumentException    Type is null.

Force the given class to be loaded fully .


public static Class getPrimitiveWrapper(final Class type)
   {
      if (!type.isPrimitive())
      {
         throw new IllegalArgumentException("type is not a primitive class");
      }

      for (int i = 0; i < PRIMITIVE_WRAPPER_MAP.length; i += 2)
      {
         if (type.equals(PRIMITIVE_WRAPPER_MAP[i]))
            return PRIMITIVE_WRAPPER_MAP[i + 1];
      }

      // should never get here, if we do then PRIMITIVE_WRAPPER_MAP
      // needs to be updated to include the missing mapping
      throw new UnreachableStatementException();
   }

Get the wrapper class for the given primitive type.

@param type    Primitive class.
@return        Wrapper class for primitive.

@exception IllegalArgumentException    Type is not a primitive class

Get the wrapper class for the given primitive type .


public static void getAllInterfaces(List allIfaces, Class c)
   {
      while (c != null)
      {
         Class[] ifaces = c.getInterfaces();
         for (int n = 0; n < ifaces.length; n ++)
         {
            allIfaces.add(ifaces[n]);
         }
         c = c.getSuperclass();
      }
   }

public static void getAllInterfaces ( List allIfaces , Class c ) { while ( c != null ) { Class [ ] ifaces = c . getInterfaces ( ) ; for ( int n = 0 ; n < ifaces . length ; n ++ ) { allIfaces . add ( ifaces [ n ] ) ; } c = c . getSuperclass ( ) ; } }

Populates a list with all the interfaces implemented by the argument
class c and all its superclasses.

@param allIfaces - the list to populate with the interfaces
@param c - the class to start scanning for interfaces

Populates a list with all the interfaces implemented by the argument class c and all its superclasses .


public static Class[] getAllUniqueInterfaces(Class c)
   {
      Set uniqueIfaces = new HashSet();
      while (c != null )
      {
         Class[] ifaces = c.getInterfaces();
         for (int n = 0; n < ifaces.length; n ++)
         {
            uniqueIfaces.add(ifaces[n]);
         }
         c = c.getSuperclass();
      }
      return (Class[])uniqueIfaces.toArray(new Class[uniqueIfaces.size()]);
   }

public static Class [ ] getAllUniqueInterfaces ( Class c ) { Set uniqueIfaces = new HashSet ( ) ; while ( c != null ) { Class [ ] ifaces = c . getInterfaces ( ) ; for ( int n = 0 ; n < ifaces . length ; n ++ ) { uniqueIfaces . add ( ifaces [ n ] ) ; } c = c . getSuperclass ( ) ; } return ( Class [ ] ) uniqueIfaces . toArray ( new Class [ uniqueIfaces . size ( ) ] ) ; }

Returns an array containing all the unique interfaces implemented
by the argument class c and all its superclasses. Interfaces that
appear multiple times through inheritence are only accounted for once.

@param c - the class to start scanning for interfaces
@return the interfaces

Returns an array containing all the unique interfaces implemented by the argument class c and all its superclasses . Interfaces that appear multiple times through inheritence are only accounted for once .


public static boolean isPrimitiveWrapper(final Class type)
   {
      for (int i = 0; i < PRIMITIVE_WRAPPER_MAP.length; i += 2)
      {
         if (type.equals(PRIMITIVE_WRAPPER_MAP[i + 1]))
         {
            return true;
         }
      }

      return false;
   }

public static boolean isPrimitiveWrapper ( final Class type ) { for ( int i = 0 ; i < PRIMITIVE_WRAPPER_MAP . length ; i += 2 ) { if ( type . equals ( PRIMITIVE_WRAPPER_MAP [ i + 1 ] ) ) { return true ; } } return false ; }

Check if the given class is a primitive wrapper class.

@param type    Class to check.
@return        True if the class is a primitive wrapper.

Check if the given class is a primitive wrapper class .


public static Object instantiate(Class expected, String property, String defaultClassName)
   {
      String className = getProperty(property, defaultClassName);
      Class clazz = null;
      try
      {
         clazz = loadClass(className);
      }
      catch (ClassNotFoundException e)
      {
         throw new NestedRuntimeException("Cannot load class " + className, e);
      }
      Object result = null;
      try
      {
         result = clazz.newInstance();
      }
      catch (InstantiationException e)
      {
         throw new NestedRuntimeException("Error instantiating " + className, e);
      }
      catch (IllegalAccessException e)
      {
         throw new NestedRuntimeException("Error instantiating " + className, e);
      }
      if (expected.isAssignableFrom(clazz) == false)
         throw new NestedRuntimeException("Class " + className + " from classloader " + clazz.getClassLoader() +
            " is not of the expected class " + expected + " loaded from " + expected.getClassLoader());
      return result;
   }

public
static
Object
instantiate
(
Class
expected
,
String
property
,
String
defaultClassName
)
{
String
className
=
getProperty
(
property
,
defaultClassName
)
;
Class
clazz
=
;
try
{
clazz
=
loadClass
(
className
)
;
}
catch
(
ClassNotFoundException
e
)
{
throw
new
NestedRuntimeException
(
"Cannot load class "
+
className
,
e
)
;
}
Object
result
=
;
try
{
result
=
clazz
.
newInstance
(
)
;
}
catch
(
InstantiationException
e
)
{
throw
new
NestedRuntimeException
(
"Error instantiating "
+
className
,
e
)
;
}
catch
(
IllegalAccessException
e
)
{
throw
new
NestedRuntimeException
(
"Error instantiating "
+
className
,
e
)
;
}
if
(
expected
.
isAssignableFrom
(
clazz
)
==
false
)
throw
new
NestedRuntimeException
(
"Class "
+
className
+
" from classloader "
+
clazz
.
getClassLoader
(
)
+
" is not of the expected class "
+
expected
+
" loaded from "
+
expected
.
getClassLoader
(
)
)
;
return
result
;
}

Instantiate a java class object

@param expected the expected class type
@param property the system property defining the class
@param defaultClassName the default class name
@return the instantiated object


public final static Method getAttributeGetter(Class cls, String attr) throws NoSuchMethodException
   {
      StringBuffer buf = new StringBuffer(attr.length() + 3);
      buf.append("get");
      if(Character.isLowerCase(attr.charAt(0)))
      {
         buf.append(Character.toUpperCase(attr.charAt(0)))
            .append(attr.substring(1));
      }
      else
      {
         buf.append(attr);
      }

      try
      {
         return cls.getMethod(buf.toString(), (Class[]) null);
      }
      catch (NoSuchMethodException e)
      {
         buf.replace(0, 3, "is");
         return cls.getMethod(buf.toString(), (Class[]) null);
      }
   }

public final static Method getAttributeGetter ( Class cls , String attr ) throws NoSuchMethodException { StringBuffer buf = new StringBuffer ( attr . length ( ) + 3 ) ; buf . append ( "get" ) ; if ( Character . isLowerCase ( attr . charAt ( 0 ) ) ) { buf . append ( Character . toUpperCase ( attr . charAt ( 0 ) ) ) . append ( attr . substring ( 1 ) ) ; } else { buf . append ( attr ) ; } try { return cls . getMethod ( buf . toString ( ) , ( Class [ ] ) null ) ; } catch ( NoSuchMethodException e ) { buf . replace ( 0 , 3 , "is" ) ; return cls . getMethod ( buf . toString ( ) , ( Class [ ] ) null ) ; } }

Returns attribute's getter method. If the method not found then NoSuchMethodException will be thrown.
@param cls  the class the attribute belongs too
@param attr  the attribute's name
@return  attribute's getter method
@throws NoSuchMethodException  if the getter was not found

Returns attribute s getter method . If the method not found then NoSuchMethodException will be thrown .


public final static Method getAttributeSetter(Class cls, String attr, Class type) throws NoSuchMethodException
   {
      StringBuffer buf = new StringBuffer(attr.length() + 3);
      buf.append("set");
      if(Character.isLowerCase(attr.charAt(0)))
      {
         buf.append(Character.toUpperCase(attr.charAt(0)))
            .append(attr.substring(1));
      }
      else
      {
         buf.append(attr);
      }

      return cls.getMethod(buf.toString(), new Class[]{type});
   }

public final static Method getAttributeSetter ( Class cls , String attr , Class type ) throws NoSuchMethodException { StringBuffer buf = new StringBuffer ( attr . length ( ) + 3 ) ; buf . append ( "set" ) ; if ( Character . isLowerCase ( attr . charAt ( 0 ) ) ) { buf . append ( Character . toUpperCase ( attr . charAt ( 0 ) ) ) . append ( attr . substring ( 1 ) ) ; } else { buf . append ( attr ) ; } return cls . getMethod ( buf . toString ( ) , new Class [ ] { type } ) ; }

Returns attribute's setter method. If the method not found then NoSuchMethodException will be thrown.
@param cls   the class the attribute belongs to
@param attr  the attribute's name
@param type  the attribute's type
@return  attribute's setter method
@throws NoSuchMethodException  if the setter was not found

Returns attribute s setter method . If the method not found then NoSuchMethodException will be thrown .


private final static Class convertToJavaClass(String name,
                                                 ClassLoader cl)
      throws ClassNotFoundException
   {
      int arraySize = 0;
      while (name.endsWith("[]"))
      {
         name = name.substring(0, name.length() - 2);
         arraySize++;
      }

      // Check for a primitive type
      Class c = (Class) PRIMITIVE_NAME_TYPE_MAP.get(name);

      if (c == null)
      {
         // No primitive, try to load it from the given ClassLoader
         try
         {
            c = cl.loadClass(name);
         }
         catch (ClassNotFoundException cnfe)
         {
            throw new ClassNotFoundException("Parameter class not found: " +
               name);
         }
      }

      // if we have an array get the array class
      if (arraySize > 0)
      {
         int[] dims = new int[arraySize];
         for (int i = 0; i < arraySize; i++)
         {
            dims[i] = 1;
         }
         c = Array.newInstance(c, dims).getClass();
      }

      return c;
   }

Convert a given String into the appropriate Class.

@param name Name of class
@param cl ClassLoader to use

@return The class for the given name

@throws ClassNotFoundException When the class could not be found by
the specified ClassLoader

Convert a given String into the appropriate Class .


private static String getProperty(final String name, final String defaultValue)
   {
      return (String) AccessController.doPrivileged(
      new PrivilegedAction()
      {
         public Object run()
         {
            return System.getProperty(name, defaultValue);
         }

      });
   }

private static String getProperty ( final String name , final String defaultValue ) { return ( String ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { return System . getProperty ( name , defaultValue ) ; } } ) ; }

Get a system property

@param name the property name
@param defaultValue the default value


public static String[] getFilenames(final String propertyName)
      throws PropertyException
   {
      String filenames[];

      // check for singleton property first
      Object filename = PropertyManager.getProperty(propertyName);
      if (filename != null) {
         filenames = new String[] { String.valueOf(filename) };
      }
      else {
         // if no singleton property exists then look for array props
         filenames = PropertyManager.getArrayProperty(propertyName);
      }

      return filenames;
   }

Get an array of filenames to load.

@param propertyName  Property to read filenames from.
@return              Array of filenames.
@throws PropertyException


protected final void maintain() {
      WeakObject weak;
      while ((weak = (WeakObject)queue.poll()) != null) {
         set.remove(weak);
      }
   }

protected final void maintain ( ) { WeakObject weak ; while ( ( weak = ( WeakObject ) queue . poll ( ) ) != null ) { set . remove ( weak ) ; } }

Maintain the elements in the set.  Removes objects from the set that
have been reclaimed due to GC.

Maintain the elements in the set . Removes objects from the set that have been reclaimed due to GC .


public Iterator iterator() {
      return new Iterator() {

            /** The set's iterator */
            Iterator iter = set.iterator();

            /** JBCOMMON-24, handle null values and multiple invocations of hasNext() */
            Object UNKNOWN = new Object();

            /** The next available object. */
            Object next = UNKNOWN;

            public boolean hasNext() {
               if (next != UNKNOWN) {
                  return true;
               }
               while (iter.hasNext()) {
                  WeakObject weak = (WeakObject)iter.next();
                  Object obj = null;
                  if (weak != null && (obj = weak.get()) == null) {
                     // object has been reclaimed by the GC
                     continue;
                  }
                  next = obj;
                  return true;
               }
               return false;
            }

            public Object next() {
               if ((next == UNKNOWN) && !hasNext()) {
                  throw new NoSuchElementException();
               }
               Object obj = next;
               next = UNKNOWN;

               return obj;
            }

            public void remove() {
               iter.remove();
            }
         };
   }

Return an iteration over the elements in the set.

@return  An iteration over the elements in the set.

Return an iteration over the elements in the set .


public URLLister createURLLister(String protocol) throws MalformedURLException {
      try {
         String className = (String) classes.get(protocol);
         if (className == null) {
            throw new MalformedURLException("No lister class defined for protocol "+protocol);
         }

         Class<?> clazz = Thread.currentThread().getContextClassLoader().loadClass(className);
         return (URLLister) clazz.newInstance();
      } catch (ClassNotFoundException e) {
         throw new MalformedURLException(e.getMessage());
      } catch (InstantiationException e) {
         throw new MalformedURLException(e.getMessage());
      } catch (IllegalAccessException e) {
         throw new MalformedURLException(e.getMessage());
      }
   }

public
URLLister
createURLLister
(
String
protocol
)
throws
MalformedURLException
{
try
{
String
className
=
(
String
)
classes
.
get
(
protocol
)
;
if
(
className
==
)
{
throw
new
MalformedURLException
(
"No lister class defined for protocol "
+
protocol
)
;
}
Class
<
>
clazz
=
Thread
.
currentThread
(
)
.
getContextClassLoader
(
)
.
loadClass
(
className
)
;
return
(
URLLister
)
clazz
.
newInstance
(
)
;
}
catch
(
ClassNotFoundException
e
)
{
throw
new
MalformedURLException
(
e
.
getMessage
(
)
)
;
}
catch
(
InstantiationException
e
)
{
throw
new
MalformedURLException
(
e
.
getMessage
(
)
)
;
}
catch
(
IllegalAccessException
e
)
{
throw
new
MalformedURLException
(
e
.
getMessage
(
)
)
;
}
}

Create a URL lister for the supplied protocol
@param protocol the protocol
@return a URLLister capable of listing URLs of that protocol
@throws MalformedURLException if no lister could be found for the protocol


@SuppressWarnings("unchecked")
   public Set entrySet()
   {
      final Set superSet = super.entrySet(true);

      return new java.util.AbstractSet()
      {
         private boolean isInGroup(Map.Entry entry)
         {
            String key = (String) entry.getKey();
            return key.startsWith(basename);
         }

         public int size()
         {
            Iterator iter = superSet.iterator();
            int count = 0;
            while (iter.hasNext())
            {
               Map.Entry entry = (Map.Entry) iter.next();
               if (isInGroup(entry))
               {
                  count++;
               }
            }

            return count;
         }

         public Iterator iterator()
         {
            return new Iterator()
            {
               private Iterator iter = superSet.iterator();

               private Object next;

               public boolean hasNext()
               {
                  if (next != null)
                     return true;

                  while (next == null)
                  {
                     if (iter.hasNext())
                     {
                        Map.Entry entry = (Map.Entry) iter.next();
                        if (isInGroup(entry))
                        {
                           next = entry;
                           return true;
                        }
                     }
                     else
                     {
                        break;
                     }
                  }

                  return false;
               }

               public Object next()
               {
                  if (next == null)
                     throw new java.util.NoSuchElementException();

                  Object obj = next;
                  next = null;

                  return obj;
               }

               public void remove()
               {
                  iter.remove();
               }
            };
         }
      };
   }

@ SuppressWarnings ( "unchecked" ) public Set entrySet ( ) { final Set superSet = super . entrySet ( true ) ; return new java . util . AbstractSet ( ) { private boolean isInGroup ( Map . Entry entry ) { String key = ( String ) entry . getKey ( ) ; return key . startsWith ( basename ) ; } public int size ( ) { Iterator iter = superSet . iterator ( ) ; int count = 0 ; while ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; if ( isInGroup ( entry ) ) { count ++ ; } } return count ; } public Iterator iterator ( ) { return new Iterator ( ) { private Iterator iter = superSet . iterator ( ) ; private Object next ; public boolean hasNext ( ) { if ( next != null ) return true ; while ( next == null ) { if ( iter . hasNext ( ) ) { Map . Entry entry = ( Map . Entry ) iter . next ( ) ; if ( isInGroup ( entry ) ) { next = entry ; return true ; } } else { break ; } } return false ; } public Object next ( ) { if ( next == null ) throw new java . util . NoSuchElementException ( ) ; Object obj = next ; next = null ; return obj ; } public void remove ( ) { iter . remove ( ) ; } } ; } } ; }

Returns an entry set for all properties in this group.

<p>
This is currently ver inefficient, but should get the
job done for now.

Returns an entry set for all properties in this group .


protected void addPropertyListener(final BoundPropertyListener listener)
   {
      // get the bound property name
      String name = makePropertyName(listener.getPropertyName());

      // get the bound listener list for the property
      List list = (List) boundListeners.get(name);

      // if list is null, then add a new list
      if (list == null)
      {
         list = new ArrayList();
         boundListeners.put(name, list);
      }

      // if listener is not in the list already, then add it
      if (!list.contains(listener))
      {
         list.add(listener);
         // notify listener that is is bound
         listener.propertyBound(this);
      }
   }

Add a bound property listener.

<p>Generates a fully qualified property name and adds the listener
under that name.

@param listener   Bound property listener to add.


protected boolean removePropertyListener(final BoundPropertyListener listener)
   {
      // get the bound property name
      String name = makePropertyName(listener.getPropertyName());

      // get the bound listener list for the property
      List list = (List) boundListeners.get(name);
      boolean removed = false;
      if (list != null)
      {
         removed = list.remove(listener);

         // notify listener that is was unbound
         if (removed)
            listener.propertyUnbound(this);
      }

      return removed;
   }

Remove a bound property listener.

<p>Generates a fully qualified property name and removes the listener
under that name.

@param listener   Bound property listener to remove.
@return           True if listener was removed.


public static final boolean isNull(final String value, final boolean trim, final boolean empty)
   {
      // For backwards compatibility
      if (disableIsNull)
         return false;
      // No value?
      if (value == null)
         return true;
      // Trim the text when requested
      String trimmed = trim ? value.trim() : value;
      // Is the empty string null?
      if (empty && trimmed.length() == 0)
         return true;
      // Just check it.
      return NULL.equalsIgnoreCase(trimmed);
   }

public
static
final
boolean
isNull
(
final
String
value
,
final
boolean
trim
,
final
boolean
empty
)
{
// For backwards compatibility
if
(
disableIsNull
)
return
false
;
// No value?
if
(
value
==
)
return
true
;
// Trim the text when requested
String
trimmed
=
trim
value
.
trim
(
)
:
value
;
// Is the empty string null?
if
(
empty
&&
trimmed
.
length
(
)
==
0
)
return
true
;
// Just check it.
return
.
equalsIgnoreCase
(
trimmed
)
;
}

Whether a string is interpreted as the null value

@param value the value
@param trim whether to trim the string
@param empty whether to include the empty string as null
@return true when the string has the value null


public static PropertyEditor findEditor(final String typeName)
      throws ClassNotFoundException
   {
      // see if it is a primitive type first
      Class<?> type = Classes.getPrimitiveTypeForName(typeName);
      if (type == null)
      {
         // nope try look up
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
         type = loader.loadClass(typeName);
      }

      return PropertyEditorManager.findEditor(type);
   }

public
static
PropertyEditor
findEditor
(
final
String
typeName
)
throws
ClassNotFoundException
{
// see if it is a primitive type first
Class
<
>
type
=
Classes
.
getPrimitiveTypeForName
(
typeName
)
;
if
(
type
==
)
{
// nope try look up
ClassLoader
loader
=
Thread
.
currentThread
(
)
.
getContextClassLoader
(
)
;
type
=
loader
.
loadClass
(
typeName
)
;
}
return
PropertyEditorManager
.
findEditor
(
type
)
;
}

Locate a value editor for a given target type.

@param typeName    The class name of the object to be edited.
@return            An editor for the given type or null if none was found.
@throws ClassNotFoundException when the class could not be found

Locate a value editor for a given target type .


public static void registerEditor(final String typeName,
                                     final String editorTypeName)
      throws ClassNotFoundException
   {
      ClassLoader loader = Thread.currentThread().getContextClassLoader();
      Class<?> type = loader.loadClass(typeName);
      Class<?> editorType = loader.loadClass(editorTypeName);

      PropertyEditorManager.registerEditor(type, editorType);
   }

public static void registerEditor ( final String typeName , final String editorTypeName ) throws ClassNotFoundException { ClassLoader loader = Thread . currentThread ( ) . getContextClassLoader ( ) ; Class < ? > type = loader . loadClass ( typeName ) ; Class < ? > editorType = loader . loadClass ( editorTypeName ) ; PropertyEditorManager . registerEditor ( type , editorType ) ; }

Register an editor class to be used to editor values of a given target class.

@param typeName         The classname of the objetcs to be edited.
@param editorTypeName   The class of the editor.
@throws ClassNotFoundException when the class could not be found

Register an editor class to be used to editor values of a given target class .


public static Object convertValue(String text, String typeName)
         throws ClassNotFoundException, IntrospectionException
   {
      // see if it is a primitive type first
      Class<?> typeClass = Classes.getPrimitiveTypeForName(typeName);
      if (typeClass == null)
      {
         ClassLoader loader = Thread.currentThread().getContextClassLoader();
         typeClass = loader.loadClass(typeName);
      }

      PropertyEditor editor = PropertyEditorManager.findEditor(typeClass);
      if (editor == null)
      {
         throw new IntrospectionException
               ("No property editor for type=" + typeClass);
      }

      editor.setAsText(text);
      return editor.getValue();
   }

public
static
Object
convertValue
(
String
text
,
String
typeName
)
throws
ClassNotFoundException
,
IntrospectionException
{
// see if it is a primitive type first
Class
<
>
typeClass
=
Classes
.
getPrimitiveTypeForName
(
typeName
)
;
if
(
typeClass
==
)
{
ClassLoader
loader
=
Thread
.
currentThread
(
)
.
getContextClassLoader
(
)
;
typeClass
=
loader
.
loadClass
(
typeName
)
;
}
PropertyEditor
editor
=
PropertyEditorManager
.
findEditor
(
typeClass
)
;
if
(
editor
==
)
{
throw
new
IntrospectionException
(
"No property editor for type="
+
typeClass
)
;
}
editor
.
setAsText
(
text
)
;
return
editor
.
getValue
(
)
;
}

Convert a string value into the true value for typeName using the
PropertyEditor associated with typeName.

@param text the string represention of the value. This is passed to
the PropertyEditor.setAsText method.
@param typeName the fully qualified class name of the true value type
@return the PropertyEditor.getValue() result
@exception ClassNotFoundException thrown if the typeName class cannot
be found
@exception IntrospectionException thrown if a PropertyEditor for typeName
cannot be found

Convert a string value into the true value for typeName using the PropertyEditor associated with typeName .


public ClassLoader getContextClassLoader(final Thread thread)
   {
      return (ClassLoader) AccessController.doPrivileged(new PrivilegedAction()
      {
         public Object run()
         {
            return thread.getContextClassLoader();
         }
      });
   }

public ClassLoader getContextClassLoader ( final Thread thread ) { return ( ClassLoader ) AccessController . doPrivileged ( new PrivilegedAction ( ) { public Object run ( ) { return thread . getContextClassLoader ( ) ; } } ) ; }

Retrieve the context classloader for the given thread

@param thread the thread
@return the context classloader


public static ApplicationDeadlockException isADE(Throwable t)
   {
      while (t!=null)
      {
         if (t instanceof ApplicationDeadlockException)
         {
            return (ApplicationDeadlockException)t;
         }
         else
         {
            t = t.getCause();
         }
      }
      return null;
   }

public static ApplicationDeadlockException isADE ( Throwable t ) { while ( t != null ) { if ( t instanceof ApplicationDeadlockException ) { return ( ApplicationDeadlockException ) t ; } else { t = t . getCause ( ) ; } } return null ; }

Detects exception contains is or a ApplicationDeadlockException.
@param t
@return  true when it is a deadlock

Detects exception contains is or a ApplicationDeadlockException .


public Timeout schedule(long time, TimeoutTarget target)
   {
      if (cancelled.get())
         throw new IllegalStateException("TimeoutFactory has been cancelled");
      if (time < 0)
         throw new IllegalArgumentException("Negative time");
      if (target == null)
         throw new IllegalArgumentException("Null timeout target");

      return queue.offer(time, target);
   }

public
Timeout
schedule
(
long
time
,
TimeoutTarget
target
)
{
if
(
cancelled
.
get
(
)
)
throw
new
IllegalStateException
(
"TimeoutFactory has been cancelled"
)
;
if
(
time
<
0
)
throw
new
IllegalArgumentException
(
"Negative time"
)
;
if
(
target
==
)
throw
new
IllegalArgumentException
(
"Null timeout target"
)
;
return
queue
.
offer
(
time
,
target
)
;
}

Schedules a new timeout.

@param time absolute time
@param target target to fire
@return the timeout


private void doWork()
   {
      while (cancelled.get() == false)
      {
         TimeoutExt work = queue.take();
         // Do work, if any
         if (work != null)
         {
            // Wrap the TimeoutExt with a runnable that invokes the target callback
            TimeoutWorker worker = new TimeoutWorker(work);
            try
            {
               threadPool.run(worker);
            }
            catch (Throwable t)
            {
               // protect the worker thread from pool enqueue errors
               ThrowableHandler.add(ThrowableHandler.Type.ERROR, t);
            }
            synchronized (work)
            {
               work.done();
            }
         }
      }

      // TimeoutFactory was cancelled
      queue.cancel();
   }


public static Context createSubcontext(Context ctx, String name) throws NamingException
   {
      Name n = ctx.getNameParser("").parse(name);
      return createSubcontext(ctx, n);
   }

public static Context createSubcontext ( Context ctx , String name ) throws NamingException { Name n = ctx . getNameParser ( "" ) . parse ( name ) ; return createSubcontext ( ctx , n ) ; }

Create a subcontext including any intermediate contexts.
@param ctx the parent JNDI Context under which value will be bound
@param name the name relative to ctx of the subcontext.
@return The new or existing JNDI subcontext
@throws javax.naming.NamingException on any JNDI failure

Create a subcontext including any intermediate contexts .


public static Object lookup(String name, Class<?> clazz) throws Exception
   {
      InitialContext ctx = new InitialContext();
      try
      {
         return lookup(ctx, name, clazz);
      }
      finally
      {
         ctx.close();
      }
   }

public static Object lookup ( String name , Class < ? > clazz ) throws Exception { InitialContext ctx = new InitialContext ( ) ; try { return lookup ( ctx , name , clazz ) ; } finally { ctx . close ( ) ; } }

Lookup an object in the default initial context

@param name the name to lookup
@param clazz the expected type
@return the object
@throws Exception for any error


protected static void checkObject(Context context, String name, Object object, Class clazz) throws Exception
   {
      Class objectClass = object.getClass();
      if (clazz.isAssignableFrom(objectClass) == false)
      {
         StringBuffer buffer = new StringBuffer(100);
         buffer.append("Object at '").append(name);
         buffer.append("' in context ").append(context.getEnvironment());
         buffer.append(" is not an instance of ");
         appendClassInfo(buffer, clazz);
         buffer.append(" object class is ");
         appendClassInfo(buffer, object.getClass());
         throw new ClassCastException(buffer.toString());
      }
   }

protected
static
void
checkObject
(
Context
context
,
String
name
,
Object
object
,
Class
clazz
)
throws
Exception
{
Class
objectClass
=
object
.
getClass
(
)
;
if
(
clazz
.
isAssignableFrom
(
objectClass
)
==
false
)
{
StringBuffer
buffer
=
new
StringBuffer
(
100
)
;
buffer
.
append
(
"Object at '"
)
.
append
(
name
)
;
buffer
.
append
(
"' in context "
)
.
append
(
context
.
getEnvironment
(
)
)
;
buffer
.
append
(
" is not an instance of "
)
;
appendClassInfo
(
buffer
,
clazz
)
;
buffer
.
append
(
" object class is "
)
;
appendClassInfo
(
buffer
,
object
.
getClass
(
)
)
;
throw
new
ClassCastException
(
buffer
.
toString
(
)
)
;
}
}

Checks an object implements the given class

@param context the context
@param name the name to lookup
@param object the object
@param clazz the expected type
@throws Exception for any error


protected static void appendClassInfo(StringBuffer buffer, Class clazz)
   {
      buffer.append("[class=").append(clazz.getName());
      buffer.append(" classloader=").append(clazz.getClassLoader());
      buffer.append(" interfaces={");
      Class[] interfaces = clazz.getInterfaces();
      for (int i=0; i<interfaces.length; ++i)
      {
         if (i > 0)
            buffer.append(", ");
         buffer.append("interface=").append(interfaces[i].getName());
         buffer.append(" classloader=").append(interfaces[i].getClassLoader());
      }
      buffer.append("}]");
   }

protected
static
void
appendClassInfo
(
StringBuffer
buffer
,
Class
clazz
)
{
buffer
.
append
(
"[class="
)
.
append
(
clazz
.
getName
(
)
)
;
buffer
.
append
(
" classloader="
)
.
append
(
clazz
.
getClassLoader
(
)
)
;
buffer
.
append
(
" interfaces={"
)
;
Class
[
]
interfaces
=
clazz
.
getInterfaces
(
)
;
for
(
int
i
=
0
;
i
<
interfaces
.
length
;
++
i
)
{
if
(
i
>
0
)
buffer
.
append
(
", "
)
;
buffer
.
append
(
"interface="
)
.
append
(
interfaces
[
i
]
.
getName
(
)
)
;
buffer
.
append
(
" classloader="
)
.
append
(
interfaces
[
i
]
.
getClassLoader
(
)
)
;
}
buffer
.
append
(
"}]"
)
;
}

Append Class Info

@param buffer the buffer to append to
@param clazz the class to describe


public Transition getTransition(String name)
   {
      Transition t = (Transition) allowedTransitions.get(name);
      return t;
   }

public Transition getTransition ( String name ) { Transition t = ( Transition ) allowedTransitions . get ( name ) ; return t ; }

Lookup an allowed transition given its name.

@param name - the name of a valid transition from this state.
@return the valid transition if it exists, null otherwise.

Lookup an allowed transition given its name .


private synchronized void readProperties() {
    try {
      propertyFileURI = CatalogManager.class.getResource("/"+propertyFile);
      InputStream in =
	CatalogManager.class.getResourceAsStream("/"+propertyFile);
      if (in==null) {
	if (!ignoreMissingProperties) {
	  System.err.println("Cannot find "+propertyFile);
	  // there's no reason to give this warning more than once
	  ignoreMissingProperties = true;
	}
	return;
      }
      resources = new PropertyResourceBundle(in);
    } catch (MissingResourceException mre) {
      if (!ignoreMissingProperties) {
	System.err.println("Cannot read "+propertyFile);
      }
    } catch (java.io.IOException e) {
      if (!ignoreMissingProperties) {
	System.err.println("Failure trying to read "+propertyFile);
      }
    }

    // This is a bit of a hack. After we've successfully read the properties,
    // use them to set the default debug level, if the user hasn't already set
    // the default debug level.
    if (verbosity == null) {
      try {
	String verbStr = resources.getString("verbosity");
	int verb = Integer.parseInt(verbStr.trim());
	debug.setDebug(verb);
	verbosity = new Integer(verb);
      } catch (Exception e) {
	// nop
      }
    }
  }

Load the properties from the propertyFile and build the
resources from it.

Load the properties from the propertyFile and build the resources from it .


private int queryVerbosity () {
    String verbStr = System.getProperty(pVerbosity);

    if (verbStr == null) {
      if (resources==null) readProperties();
      if (resources==null) return defaultVerbosity;
      try {
	verbStr = resources.getString("verbosity");
      } catch (MissingResourceException e) {
	return defaultVerbosity;
      }
    }

    try {
      int verb = Integer.parseInt(verbStr.trim());
      return verb;
    } catch (Exception e) {
      System.err.println("Cannot parse verbosity: \"" + verbStr + "\"");
      return defaultVerbosity;
    }
  }

private
int
queryVerbosity
(
)
{
String
verbStr
=
System
.
getProperty
(
pVerbosity
)
;
if
(
verbStr
==
)
{
if
(
resources
==
)
readProperties
(
)
;
if
(
resources
==
)
return
defaultVerbosity
;
try
{
verbStr
=
resources
.
getString
(
"verbosity"
)
;
}
catch
(
MissingResourceException
e
)
{
return
defaultVerbosity
;
}
}
try
{
int
verb
=
Integer
.
parseInt
(
verbStr
.
trim
(
)
)
;
return
verb
;
}
catch
(
Exception
e
)
{
System
.
err
.
println
(
"Cannot parse verbosity: \""
+
verbStr
+
"\""
)
;
return
defaultVerbosity
;
}
}

Obtain the verbosity setting from the properties.

@return The verbosity level from the propertyFile or the
defaultVerbosity.

Obtain the verbosity setting from the properties .


private boolean queryRelativeCatalogs () {
    if (resources==null) readProperties();

    if (resources==null) return defaultRelativeCatalogs;

    try {
      String allow = resources.getString("relative-catalogs");
      return (allow.equalsIgnoreCase("true")
	      || allow.equalsIgnoreCase("yes")
	      || allow.equalsIgnoreCase("1"));
    } catch (MissingResourceException e) {
      return defaultRelativeCatalogs;
    }
  }

private boolean queryRelativeCatalogs ( ) { if ( resources == null ) readProperties ( ) ; if ( resources == null ) return defaultRelativeCatalogs ; try { String allow = resources . getString ( "relative-catalogs" ) ; return ( allow . equalsIgnoreCase ( "true" ) || allow . equalsIgnoreCase ( "yes" ) || allow . equalsIgnoreCase ( "1" ) ) ; } catch ( MissingResourceException e ) { return defaultRelativeCatalogs ; } }

Obtain the relativeCatalogs setting from the properties.

@return The relativeCatalogs setting from the propertyFile or the
defaultRelativeCatalogs.

Obtain the relativeCatalogs setting from the properties .


private String queryCatalogFiles () {
    String catalogList = System.getProperty(pFiles);
    fromPropertiesFile = false;

    if (catalogList == null) {
      if (resources == null) readProperties();
      if (resources != null) {
	try {
	  catalogList = resources.getString("catalogs");
	  fromPropertiesFile = true;
	} catch (MissingResourceException e) {
	  System.err.println(propertyFile + ": catalogs not found.");
	  catalogList = null;
	}
      }
    }

    if (catalogList == null) {
      catalogList = defaultCatalogFiles;
    }

    return catalogList;
  }

private
String
queryCatalogFiles
(
)
{
String
catalogList
=
System
.
getProperty
(
pFiles
)
;
fromPropertiesFile
=
false
;
if
(
catalogList
==
)
{
if
(
resources
==
)
readProperties
(
)
;
if
(
resources
!=
)
{
try
{
catalogList
=
resources
.
getString
(
"catalogs"
)
;
fromPropertiesFile
=
true
;
}
catch
(
MissingResourceException
e
)
{
System
.
err
.
println
(
propertyFile
+
": catalogs not found."
)
;
catalogList
=
;
}
}
}
if
(
catalogList
==
)
{
catalogList
=
defaultCatalogFiles
;
}
return
catalogList
;
}

Obtain the list of catalog files from the properties.

@return A semicolon delimited list of catlog file URIs

Obtain the list of catalog files from the properties .


public Vector getCatalogFiles() {
    if (catalogFiles == null) {
      catalogFiles = queryCatalogFiles();
    }

    StringTokenizer files = new StringTokenizer(catalogFiles, ";");
    Vector catalogs = new Vector();
    while (files.hasMoreTokens()) {
      String catalogFile = files.nextToken();
      URL absURI = null;

      if (fromPropertiesFile && !relativeCatalogs()) {
	try {
	  absURI = new URL(propertyFileURI, catalogFile);
	  catalogFile = absURI.toString();
	} catch (MalformedURLException mue) {
	  absURI = null;
	}
      }

      catalogs.add(catalogFile);
    }

    return catalogs;
  }

public Vector getCatalogFiles ( ) { if ( catalogFiles == null ) { catalogFiles = queryCatalogFiles ( ) ; } StringTokenizer files = new StringTokenizer ( catalogFiles , ";" ) ; Vector catalogs = new Vector ( ) ; while ( files . hasMoreTokens ( ) ) { String catalogFile = files . nextToken ( ) ; URL absURI = null ; if ( fromPropertiesFile && ! relativeCatalogs ( ) ) { try { absURI = new URL ( propertyFileURI , catalogFile ) ; catalogFile = absURI . toString ( ) ; } catch ( MalformedURLException mue ) { absURI = null ; } } catalogs . add ( catalogFile ) ; } return catalogs ; }

Return the current list of catalog files.

@return A vector of the catalog file names or null if no catalogs
are available in the properties.

Return the current list of catalog files .